且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

opendir将不接受字符串变量,但会接受纯字符串

更新时间:2023-02-18 19:37:26

char * fgets(char * str,int num, FILE * stream);



fgets()从流中读取字符并将其作为C字符串存储到str中直到(num-1)个字符已被读取,或者换行符或文件结尾,以先到者为准。



换行符使fgets停止读取,但是它被视为一个有效的字符,并被包含在复制到str中的字符串中。



在复制到str的字符后,自动附加一个终止空字符。 p>

所以你需要从文件名中删除 \\\
,然后将其传递给opendir()进一步处理。 / p>




  system(clear); 
DIR * dirp;
struct dirent * dp;
printf(输入目录名:);
fgets(buffer2,100,stdin);

//从缓冲区2中删除拖尾\\\

strtok(buffer2,\\\
);

if((dirp = opendir(buffer2))== NULL)
printf(Could not open directory\\\
);
else {
while((dp = readdir(dirp))!= NULL)
printf(%s\\\
,dp-> d_name);
closedir(dirp);
}

printf(命中输入返回选择);
getchar();






opendir 调用get失败,你不需要去与 readdir ,所以把那部分在其他


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();

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