【问题标题】:Reading from file into structure, using C使用C从文件读入结构
【发布时间】:2014-04-05 21:48:04
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

FILE * fptr;
struct invStruct
{
int frame;
float elec;
float vdw;
float total;
};

int main()
{
int i;
fptr = fopen("/Users/jmindrebo/C_programming/structuretest.txt", "r");
if(fptr == 0){
printf("file not found\n");
exit(1);
}

struct invStruct item[4000] = {0};
for (i=0; i<1; i++)
{
    scanf(fptr, "%d\t%.4f\t%.4f\t%4.f", &item[i].frame, item[i].elec, item[i].vdw, item[i].total);
    printf("%s\t%.4f\t%.4f\t%4.f", item[i].frame, item[i].elec, item[i].vdw, item[i].total);  
}
fclose(fptr);
return 0;
}

我对编码比较陌生,上周我才开始学习 C,所以这是迄今为止我能想到的最好的。我正在尝试将此制表符分隔的文本文件读入一个结构中,以便可以在某些计算中使用这些值。我在将文本文件的值加载到 2D 数组时遇到了麻烦,所以我认为这会更容易,同时仍然可以很好地工作。

我不断收到的错误是: /usr/include/stdio.h:274:6:注意:预期为“const char *”,但参数类型为“struct FILE *”

我已经在网上阅读了一两个小时,但我仍然没有弄清楚问题所在。任何帮助将不胜感激!

【问题讨论】:

  • 第 274 行将是 scanf 行,因此当您看到有关错误参数类型的错误时,首先要做的是检查 scanf 的文档(或跳至其声明在您的 IDE 中)并查看您的参数是否与预期的类型匹配。

标签: c


【解决方案1】:

您需要致电 fscanf 而不是 scanf。养成阅读你正在使用的函数文档的习惯,这里是scanf(3)。如果您有机会在 Linux 上编码,请输入

man scanf

并编译

gcc -Wall -Wextra -Wpedantic -g yourfile.cc -o yourprog

然后学习如何使用GDB debugger (gdb) 并运行

gdb yourprog

顺便说一句,以scanf 格式给出精度是没有用的。使用scanffscanf 的结果是很好的做法

   int nbread = fscanf(fptr, "%d %f %f %f", 
      &item[i].frame, &item[i].elec, &item[i].vdw, &item[i].total);
   if (nbread != 4) {
      fprintf(stderr, "failed to read entry #%d (%s)\n", 
              i, strerror(errno));
      exit(EXIT_FAILURE);
   }

顺便说一句,您可以删除 scanf 格式的大部分空格。我通常让他们 使格式字符串更具可读性。 你需要

   #include <string.h>
   #include <errno.h>

对于strerrorerrno,请阅读strerror(3)errno(3)

我还建议以\n 结束printf 格式字符串(因为stdout 已缓冲,请参阅stdout(3)!)或者在适当的地方使用fflush(3)

【讨论】:

    【解决方案2】:

    使用fscanf 而不是scanf,正如其他人已经说过的那样。还在扫描函数的参数前添加和号。
    您还可以从扫描格式中删除 TAB 字符(“\t”)。

    fscanf(fptr, "%d%.4f%.4f%4.f", &item[i].frame, &item[i].elec, &item[i].vdw, &item[i].total);  
    

    【讨论】:

      【解决方案3】:

      scanffscanf 是不同的。 scanf的第一个参数是格式字符串;它默认输出到stdout。你想要的是fscanf,它将输出指针作为它的第一个参数,第二个是格式字符串。见this

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 1970-01-01
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 2014-06-29
        • 2014-05-22
        相关资源
        最近更新 更多