问题
I cannot get this function to work, because for some reason opendir will not take buffer2 (declared as char buffer2[128]) as an argument properly. If I replace the variable with something like "." or "sample", it works perfectly. But doing it like this, I get a segmentation fault every time. Please help.
system("clear");
DIR *dirp;
struct dirent *dp;
printf("Enter directory name: ");
fgets(buffer2, 100, stdin);
if((dirp = opendir(buffer2)) == NULL)
printf("Could not open directory\n");
while((dp = readdir(dirp)) != NULL)
printf("%s\n", dp->d_name);
closedir(dirp);
printf("Hit enter to return to selection.");
getchar();
回答1:
char * fgets ( char * str, int num, FILE * stream );
fgets()
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
A terminating null character is automatically appended after the characters copied to str.
So you need to remove that \n
from filename and then pass it to opendir() for further process.
system("clear");
DIR *dirp;
struct dirent *dp;
printf("Enter directory name: ");
fgets(buffer2, 100, stdin);
// Lets remove tailing \n from buffer2
strtok(buffer2, "\n");
if((dirp = opendir(buffer2)) == NULL)
printf("Could not open directory\n");
else {
while((dp = readdir(dirp)) != NULL)
printf("%s\n", dp->d_name);
closedir(dirp);
}
printf("Hit enter to return to selection.");
getchar();
when opendir
call get fails you do not need to go with readdir
so put that part in else
来源:https://stackoverflow.com/questions/29839089/opendir-will-not-accept-string-variable-but-will-accept-plain-string