【问题标题】:Fscanf into a structurefscanf 变成一个结构体
【发布时间】:2014-03-24 23:39:13
【问题描述】:

我正在尝试将一些数据 fscanf 到一个结构中,编译器对代码没有问题,但是当我尝试打印它时,它甚至不打印文本。这是代码:

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

typedef struct xy {
    unsigned x;
    unsigned y;
} myStruct;

int main(void)
{
    FILE *myFile;
    myStruct *xy;
    myFile = fopen("filename.txt", "rb");

    if(fscanf(myFile, "%u %u", &xy->x, &xy->y) != 2)
        fprintf(stderr, "Error!"); exit(1);

    fclose(myFile);
    printf("x: %u, y: %u\n", xy->x, xy->y);
    return 0;
}

我需要为此分配空间吗?如果我必须这样做,你能告诉我如何去做吗?

【问题讨论】:

  • 这有点“离题”,但您应该明确检查fopen() 的返回值!始终检查您使用的系统功能的人,以了解它们是否会失败(这一点很明显)。
  • 是的,没有包含整个源代码,只是想发布相关的内容。

标签: c file-io struct scanf


【解决方案1】:

您那里没有结构。只是结构上的指针。 您可以使用malloc() 为其分配内存或声明结构本地化:

myStruct xy;

本例中无需使用 malloc。

固定:

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

typedef struct xy {
  unsigned int x;
  unsigned int y;
} myStruct;

int main(void)
{
  FILE *myFile;
  myStruct xy;
  if ((myFile = fopen("filename.txt", "rb")) == NULL)
    return (1);
  if(fscanf(myFile, "%u %u", &xy.x, &xy.y) != 2)
    {
      fprintf(stderr, "Error!");
      return (1);
    }
  fclose(myFile);
  printf("x: %u, y: %u\n", xy.x, xy.y);
  return 0;
}

【讨论】:

  • 那么那个项目在代码上是怎么做的呢?我是否仍然像现在一样引用结构(在 fscanf 和 printf 中)?
  • @imre 如果您选择使用myStruct xy,则只需将-&gt; 运算符更改为. 运算符。
  • 你尝试编译运行了吗?你有任何标准输出吗?
  • 是的,我做到了。使用包含 &lt;value&gt; &lt;value&gt; 的文件 filename.txt
  • 好的,很好。感谢您的热心帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
相关资源
最近更新 更多