I am trying to compile a program on OS-X using CodeBlocks and the GCC compiler:
extern int listFiles(void) {
struct _finddata_t myFile;
int hFile;
if ((hFile = _findfirst("*.txt", &myFile)) == -1L) {
printf("No text files in current directory.\n");
return 0;
}
printf("File name: %s File size: %d", myFile.name, myFile.size);
while (_findnext(hFile, &myFile) == 0) {
printf("File name: %s File size: %d", myFile.name, myFile.size);
}
_findclose(hFile);
return 1;
}
However, the compilation fails with this error:
error: variable has incomplete type 'struct _finddata_t'
I'm assuming that this is a Windows-only structure, for use with _findfirst and _findnext. What equivalent structure and functions could I use to compile this on OS-X?
As Igor Tandetnik commented, you should look at the functions opendir(),
readdir(),
closedir()*, and the types DIR * and struct dirent. That is the basic, low-level interface that reads each entry in a directory, presenting the names in an indeterminate order (actually, it's usually the order that the names appear in the raw directory, but that is not usually alphabetic or any other order) without any filtering.
If you want to filter the file names so that only .txt files are selected, then you have to go to more obscure parts of POSIX: scandir(). This allows you to provide a selector function (a callback) that tells scandir() when to return a given entry, and also takes a comparator function that is used to sort the list of names (as if via qsort()).
* While searching, I also found fdopendir() and
dupfd(). They're fairly new and modestly interesting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With