简体   繁体   中英

opendir will not accept string variable but will accept plain string

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM