2

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();
Luca
  • 515
  • 5
  • 17
  • 1
    Try to put the while loop and the closedir in the if block – Morb Apr 24 '15 at 05:09
  • 1
    Strings read in with `fgets` retain the new-line character at the end. Try removing it with `strtok(buffer2, "\n")` after reading. You should also check the return value of `fgets`. – M Oehm Apr 24 '15 at 05:20
  • Have you tried `strcpy(buffer2, ".")` or to confirm it is the fact your using a buffer that is the problem rather than the contents of the buffer? – John3136 Apr 24 '15 at 05:27

1 Answers1

3

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

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222
  • Alternatively, can use `scanf` with `%s`. That stops at any whitespace and does not put it into the buffer. – kaylum Apr 24 '15 at 05:35
  • @AlanAu Scanf will not take space and space may be there in dirname and with scanf you need to use fflush(stdin) to clear that extra \n character so better to use fgets() – Jeegar Patel Apr 24 '15 at 05:50