我想知道从文件中读取行的最佳方法是什么,因为我有 一个文件,我 promise 它将如下所示:
type
string table
color
string brown
height
int 120
cost
double 129.90
每次,一个词,然后我就会有 2 个词。
我知道 fscanf 返回它扫描的 var 数量的值,那就是 为什么我在这里遇到问题,因为有一次该行有 1 个参数,而下一行有 2 个参数。
第一行总是只有一个 char*,长度不超过 10,然后下一行有 3 个选项。 如果写成 int,则后面的数字也将是 int,如果写成 double 或字符串,则后面的数字也将是 int。
谢谢。
最佳答案
从文件的结构来看,我认为它可以分为一个结构体。 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;
}
读取文件后,您可以检查结构数组以查找所需的 int
、double
,具体取决于 name
的值,使用sscanf
正如某些程序员家伙所指出的。
关于c - 从 FILE 中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46659629/