从FILE读取行

时间:2017-10-10 06:05:27

标签: c input

我想知道从文件读取行的最佳方法是什么,鉴于我有 一个文件,我承诺它会如下:

type
string table
color
string brown
height
int 120
cost
double 129.90

每次,一个单词,然后我会有2个单词。

我知道fscanf返回它扫描的var数量的值,那就是 为什么我在这里遇到问题,因为有一次该行有1个参数而下一行有2个参数。

总是第一行只是一个char *,不超过10,然后下一个是3个选项.. 如果它被写成一个int,则后面的数字将是一个int,如果它是一个double或一个字符串。

谢谢你。

1 个答案:

答案 0 :(得分:1)

从文件的结构我认为它可以分组成一个结构。 fscanf可以像:

一样使用
#include <stdio.h>
#include <stdlib.h>

#define SIZE 100

typedef struct Node {
  char name[SIZE];
  char type[SIZE], value[SIZE];
} Node;

int main() {
  FILE *pFile = fopen("sample-test.txt", "r");
  if(pFile == NULL) {
    fprintf(stderr, "Error in reading file\n");
    return EXIT_FAILURE;
  }
  Node nodes[SIZE];
  int nRet, nIndex = 0;

  // Just to make sure it reads 3 tokens each time
  while((nRet = fscanf(pFile, "%s%s%s", nodes[nIndex].name, 
                       nodes[nIndex].type, nodes[nIndex].value) == 3)) 
    nIndex++;

  for(int i = 0; i < nIndex; i++)
    printf("%s %s %s\n", nodes[i].name, nodes[i].type, nodes[i].value);

  return EXIT_SUCCESS;
}

阅读完文件后,您可以检查结构数组以找到所需的intdouble,具体取决于使用name的{​​{1}}的值程序员Dude。

相关问题