terminal count files in directory
To count the number of files in a directory using C, you can make use of the dirent.h and sys/types.h headers. Here's an example code snippet that demonstrates how to accomplish this task:
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int main() {
DIR *dir;
struct dirent *entry;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
printf("Failed to open directory.\n");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
if (entry->d_type == DT_REG) { // check if the entry is a regular file
count++;
}
}
closedir(dir);
printf("Number of files in the directory: %d\n", count);
return 0;
}
This code opens the current directory using opendir(".")
and then iterates through each entry in the directory using the readdir()
function. For each entry, it checks if the entry is a regular file using entry->d_type == DT_REG
and increments the count if it is. Finally, it prints the total count of files in the directory.