c - 添加文件关闭语句导致段错误

标签 c file-io segmentation-fault

在读取文件后尝试关闭文件时,我在运行程序时遇到段错误。

    int inputDirectory()
    {
    char fileName[64];char directoryBuffer[256];FILE *fp;
    printf("\n> Please type the filename containing the list of directories. >");
    inputFix(fileName, sizeof(fileName));
    fp = fopen(fileName,"r");
    if(access(fileName, F_OK) == 0)
    {
        if (fp == 0)
        {
            printf("> Error opening file.");
            return 1;
        }
        else
        {
            if (access(fileName, R_OK) == 0)
            {
                while (fgets(directoryBuffer, sizeof(directoryBuffer), (FILE*)fp))
                {       
                    readCheck(directoryBuffer);
                    printf("%s \n", directoryBuffer);
                    getInode(directoryBuffer);
                }
            }
            else
            {
                printf("\n> File can't be read.");
            }
        }
    }
    else
    {
        printf("\n> File %s does not exist ", fileName); 
    }
    fclose(fp);
    return 0;
}

void inputFix(char string[],int length)
{
int ch, len = 0;
fgets(string, length, stdin);
string[strcspn(string, "\r\n")] = '\0';
len = strlen(string);
if (len == length - 1)
{
     while((ch = getchar()) != '\n' && ch != EOF);
}
}

void readCheck(char string[])
{
    string[strcspn(string, "\r\n")] = '\0';
}

我一直在阅读竞争条件,但据我所知,没有竞争条件?在尝试打开文件之前是否需要检查文件是否存在?是否需要包括我正在使用的一些支票?

最佳答案

查看这些行。

    if (fp == 0)
    {
        printf("> Error opening file.");
        fclose(fp);   // NOT NEEDED. REMOVE THE LINE
    }

当您无法打开文件时,您似乎不需要调用 fclose

删除该行。

关于c - 添加文件关闭语句导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23319017/

相关文章:

c++ - VS2012 LibRTMP包含c到c++

c++ - 简明、精确的 WordNet 教程?

c - 段错误(核心已转储),使用动态 vector

c- 分配和释放二维数组

java - 创建并读取UTF-8文件夹java

Java 文件 I/O -ftp 繁忙错误读取文件错误

python - 使用python3中的tarfile模块从tar中提取文本文件

c - OpenMP 奇怪的行为

c++ - 尝试打印/加载二维数组时出现段错误

c - 将具有重复值的整数数组部分排序到存储桶中的最快方法