文件I / O fopen()返回NULL

时间:2014-06-26 21:31:26

标签: c fopen

我写了以下代码:

void WriteToFile(const char** strings, const char* path, int n)
{
    FILE* fp = fopen(path, "w");
    int i;
    if(fp)
    {
        for(i = 0 ; i < n ; i++)
        {
            puts(strings[i]);
            fprintf(fp, "%s\n", strings[i]);
        }
    }
    else
    {
        printf("Error at writing to file.\n");
        exit(1);
    }

    fclose(fp);
}

我收到一个错误 - fp指向NULL - 意味着fopen()无法正常工作,很奇怪,我也打印了路径,它没有\n或其中有些奇怪的东西,它可用于我的电脑。

1 个答案:

答案 0 :(得分:2)

如果您不知道fopen失败的原因,请让计算机告诉您:

fp = fopen(path, "w");
if( fp == NULL ) {
  perror( path );
  exit(1);  /* Or handle error some other way */
}

错误消息属于stderr,而不是stdout。切勿使用printf来编写错误消息(请改用fprintf( stderr, ...)。 perror不仅会将错误消息打印到正确的位置,还会告诉您问题所在。