Antonio said:
Hi, I need help. I want to read text files contained into a directory,
but my program is unaware of how many files are contained into.
In bash there's something similar to (figure out)
for i in <dir> do
...
done
but I don't know how to do the same in C. Can you show me snippets of code?
-- Antonio
Hi, there. I guess it's not neccessary for me to explain too much. The
code example shows how to get to know the contents of the directory.
/*==================BEGIN=================*/
/*
* Name:
* list_v01.c - version 0.1 of list
* Function:
* List directory.
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h> // for Directory Operations
int
main(int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc == 1) // if there is only 1 argument
dp = opendir (".");
else if (argc == 2) { // if there are 2 arguments
if ((dp = opendir(argv[1])) == NULL) {
printf("Can't open %s\n", argv[1]);
return EXIT_FAILURE;
}
}
else { // if there are more than 2 arguments
printf("Usage: %s [DIR]\n", argv[0]);
return EXIT_FAILURE;
}
while ((dirp = readdir(dp)) != NULL)
printf ("%s\n", dirp -> d_name);
if (closedir(dp) == -1 ) {
printf("Error in closing directory.");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
/*===================END===================*/
You can do some directory operations with "dirent.h" header file. The
dirent struct inlcudes three attributes of the files contained in the
specified directory. You can get to know more about that struct in
"bit/dirent.h".
After you know how to read the directory, I guess you can do some
further operations to implement your goal.
I hope this will help a little.
Weichao Liu
===================================
Students' Robotics Lab, CS Dept.
Huai Hai Institute of Technology
===================================