【问题标题】:I don't know why the file won't open不知道为什么文件打不开
【发布时间】:2021-09-04 23:40:56
【问题描述】:

这是我的代码

#define _CRT_SECURE_NO_WARNINGS    
#include <stdio.h>    
#include <stdlib.h>

#define TRUE    1
#define FALSE   0

typedef struct {    
    int M,N;    
    int min,max;    
    int width;    
    int height;    
    unsigned char **pixels;    
}PPMIMG;
    
int fnReadPPM(char* fileNm,PPMIMG* img);

int main(int argc, char ** argv)
{    
    PPMIMG img;        

    if(fnReadPPM(argv[1], &img) != FALSE)
    {    
        return TRUE;    
    }

    return  0;
}

int fnReadPPM(char* fileNm ,PPMIMG* img)
{    
    FILE* fp;    
    fp = fopen("/users/ashton/Downloads/test.txt","rb");
    
    if(fileNm == NULL){    
        fprintf(stderr,"Unable to File ! : %s\n",fileNm);    
        return FALSE;    
    }
    
    fclose(fp);    
    return TRUE;
}

int fnWritePPM(char* fileNm, PPMIMG* img)
{    
    FILE *fp =fopen(fileNm, "w");    
    if(fp == NULL)
    {    
        fprintf(stderr, "Failed to create the file.");    
        return FALSE;    
    }        
    return TRUE;
}

这是错误代码:

Unable to File ! : (null)
Program ended with exit code: 0 

【问题讨论】:

  • 检查errno的值,或者只使用perror函数。
  • 实际上,这个特定的错误消息似乎不是由文件打开本身引起的,而是fileNm不是从命令行提供的。
  • 不要在代码的每一行之间添加空白行。它使它的可读性降低,可读性代码非常重要,尤其是对于编写它的人。
  • 使用perror() 了解您遇到的错误。
  • 那么,我应该使用fileNm以外的东西吗?

标签: c image-processing ppm


【解决方案1】:

问题最有可能在这里:

int fnReadPPM(char* fileNm ,PPMIMG* img)
{
    FILE* fp;
    fp = fopen("/users/ashton/Downloads/test.txt","rb"); // you assign fp
    
    if (fileNm == NULL){                                // and here you check for fileNm 
        fprintf(stderr,"Unable to File ! : %s\n",fileNm);
        return FALSE;
    }    
    ...

你想要这个:

int fnReadPPM(char* fileNm ,PPMIMG* img)
{
    FILE* fp;
    fp = fopen("/users/ashton/Downloads/test.txt","rb");
    
    if (fp == NULL) {
        fprintf(stderr,"Unable to open file %s.\n", fileNm);
        return FALSE;
    }    
    ...

但是在fnWritePPM 函数中你做对了。

【讨论】:

  • 非常感谢!我使用 fp 而不是 fileNm,然后该代码开始构建
【解决方案2】:

你错误地测试了 fopen 返回值:

fp = fopen("/users/ashton/Downloads/test.txt","rb");
if (fp == NULL) {    //<===== Was WRONG, you used fileNm instead of fp
    perror("Unable to File");
    return FALSE;
}

【讨论】:

  • 非常感谢!我使用 fp 而不是 fileNm,然后该代码开始构建
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
相关资源
最近更新 更多