【问题标题】:warning: incompatible pointer types passing 'char *' to parameter of type 'FILE *' (aka 'struct __sFILE *')警告:不兼容的指针类型将“char *”传递给“FILE *”类型的参数(又名“struct __sFILE *”)
【发布时间】:2018-05-23 06:16:56
【问题描述】:

我正在尝试执行我的代码,但我似乎收到了这个不兼容的警告。

int Read_Data_File(void)
{
    FILE *ptr_file;
    char *end = "0.0.0.0 none";
    char *buf;
    int endLoop = 0;

    ptr_file = fopen("CS222_Inet.txt", "r");


    if (!ptr_file) 
        return 1;

    int i = 0;

    while (!feof(ptr_file)){
        addr[i]=(struct address_t *)malloc(sizeof(struct address_t));
        fscanf(ptr_file,"%s",buf);
        if(!(strcmp(buf, end) == 0)){
            fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &addr[i]->IP2,  &addr[i]->IP3, &addr[i]->IP4, addr[i]->name);
            n++;
        }
        i++;
    }

    fclose(ptr_file);
    return 0;
}

我希望这个程序读取文件并将我的结构类型存储到我的 buf 指针中。

警告输出:

project.c:65:11: warning: incompatible pointer types passing 'char *' to
      parameter of type 'FILE *' (aka 'struct __sFILE *')
      [-Wincompatible-pointer-types]
                        fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &add...
                               ^~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/stdio.h:250:30: note: 
      passing argument to parameter here
int      fscanf(FILE * __restrict, const char * __restrict, ...) __scanf...
                                 ^

【问题讨论】:

  • 它准确地告诉你错误:你的第二个fscanf 的第一个参数是buf,它不是一个文件。此外,谷歌“while (!feof()) 总是错误的”。

标签: c file pointers char scanf


【解决方案1】:

就像错误所说:fscanf 期望它的第一个参数是FILE *,而你传递给它的是一个字符缓冲区。 如果要使用scanf 系列函数解析字符缓冲区,请使用sscanf

【讨论】:

  • 我实际上尝试了sscanf,我在接口上得到的输出说总线错误:10。我也不知道那是什么意思。你能帮我解决这个问题吗?
  • 这可能是因为您将 buf 声明为 char 指针,但没有为其分配任何内存。尝试使 buf 成为一个 char 数组或使用 malloc 动态分配一些内存并让 buf 指向它(确保它之后正确释放它)
猜你喜欢
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 2020-07-29
相关资源
最近更新 更多