-1

When I give the function the file's directory ( say /home/username/filename.txt ) I get the errors:

No such file or directory Segmentation fault (core dumped)

the part of getting the name works fine, but fopen() returns NULL My function's code is:

#define L_SIZE 128
FILE* openFile()
{
    char dir[L_SIZE];

    printf("Enter the file's directory: ");

    if(fgets( dir, L_SIZE, stdin ))
    {
        printf("\nWe got the directory: %s\n",dir);
        FILE* fp;
        if ( (fp = fopen( dir, "r" )) == NULL )
        { 
            perror("An error has occured");
            return NULL;
        }
        else
        {
            return fp;
        }
    }
    else
    {
        printf("Sorry, An error has occurs.\n");
        return NULL;
    }
}
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
Michael Heidelberg
  • 993
  • 11
  • 24

1 Answers1

2

The problem is probably related to the fact that you're using fgets() to get the input: the returning path will contain the \n char.

Try removing it (as an example, with strtok(dir, "\n");) and It will work.

n0idea
  • 732
  • 1
  • 5
  • 14