file->d_name into a variable in C
15,224
Solution 1
Not very clear what you wanted, I prefer to think you want read the file name into your varible 'fileName' and then handle that varible... Correct 2 parts:
- fileName type should be same as the struct member for assign.
the while loop......
int main(){ DIR *dir; struct dirent *file; char fileName[255]; dir = opendir("../../incoming"); while ((file = readdir(dir)) != NULL) { printf(" %s\n", file->d_name); strncpy(fileName, file->d_name, 254); fileName[254] = '\0'; printf("%s\n", fileName); } closedir(dir); return 0; }
Solution 2
You need to declare a character array of sufficient size and copy the contents of the file->d_name into it if you want to save it past the call to closedir().
If you want to simply print the name,
printf("%s\n", file->d_name);
would accomplish that.
Author by
Alexandre Lapille
Updated on June 04, 2022Comments
-
Alexandre Lapille almost 2 years
I have a probleme with a program. I need to take file name in a folder and put it in a variable. I tried that:
#define _POSIX_SOURCE #include <dirent.h> #include <errno.h> #include <sys/types.h> #undef _POSIX_SOURCE #include <stdio.h> int main() { DIR *dir; struct dirent *file; char fileName; dir = opendir("../../incoming"); while ((file = readdir(dir)) != NULL) printf(" %s\n", file->d_name); fileName = file->d_name; printf(fileName); closedir(dir); return 0; }
thx