I’m trying to create a function that scans a folder on my Windows PC and every time it does, a file called “Filter.txt” is appended with the string “Test Script”.
Now the problems are 2, the first is that the scan must be performed either in the directory c:\LOG or its subdirectories, and the second is that I do not know how to chain fopen in the directory and the name of the file.
int main(){
DIR *dir;
FILE * pFile;
char myString[100];
struct dirent *ent;
dir = opendir ("c:\\LOG");
if (dir != NULL) {
/* print all the files and directories */
while ((ent = readdir (dir)) != NULL) {
pFile = fopen ("Filter.txt","a");
if (pFile==NULL)
perror("Error");
else
fprintf(pFile,"%s\n","Test scriptIno");
fclose(pFile);
//printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* Can not open directory */
perror ("");
return EXIT_FAILURE;
}
}
For how to chain calls to
opendiryou can find plenty of answers here on SO, for example this. Useent->d_typeto check if the entry is a directory or a file.For opening a file in the directory, just use the pathname in
ent->d_nameto construct the path for thefopencall.Edit Was a little bored at work, and made a function like the one you maybe want…
Edit It seems that the
opendirandreaddirfunctions are not very well supported on Windows. Use the Windows-onlyFindFirstFileandFindNextFilein a similar fashion to my example above. See this MSDN page for an example on how to use these functions.