没有这样的文件或目录和分段错误 - 打开文件

No such file or directory and segmentation fault - opening a file

当我为函数提供文件目录(比如 /home/username/filename.txt )时,我收到错误:

No such file or directory Segmentation fault (core dumped)

获取名称的部分工作正常,但是 fopen() returns NULL 我的函数代码是:

#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;
    }
}

问题可能与您使用 fgets() 获取输入有关:返回路径将包含 \n 字符。

尝试删除它(例如,使用 strtok(dir, "\n");),它将起作用。