I am writing a C program that looks at all files in the current directory using DIR, opendir(), and readdir(), then assigning them to a dirent struct as below.
int main(int argc, char *argv[])
{
DIR *d;
char *dir_name = ".";
struct stat s;
d = opendir(dir_name);
while (1) {
struct dirent *entry;
entry = readdir(d);
if (!entry)
break;
//how to check if this is a text file before printing?
printf ("%s\n", entry->d_name);
}
closedir(d)
}
What I need to find out is how to test the file to see if it is a text file. I thought of using stat() to look at the mode. I can exclude directories this way. For binaries I thought I could look for executable bits, but that would be a problem for scripts, for instance, which are executable text files.
Any suggestions on how I might be able to programmaticaly filter for only text files?
file
and then parse its output. - Dave Newmanfork
andexec
to be able to invokefile
from your code. I like the libmagic suggestion better however. - Dave Newman