[英]fscanf() in C, format for varying length line
所以我有一个文件,其中包含以下形式的数据:
...
5,25,15,16,1,3,Dwyfor_Meirionnydd
5,34,33,26,12,22,Gower
5,7,28,35,4,23,Islwyn
2,20,12,Llanelli
5,4,5,17,7,21,Merthyr_Tydfil_and_Rhymney
5,5,4,35,28,27,Monmouth
4,5,14,19,15,Montgomeryshire
7,0,32,17,5,12,20,33,Neath
2,38,24,Newport_East
...
我需要读取每一行并将其放入结构中,以便存储第一个无符号整数,接下来的 n 个无符号整数存储在一个数组中,然后存储末尾的字符串。 例如,第二行是:
number-of-elements: 5
array: {34,33,26,12,22}
name: "Gower"
该number
告诉我们array
有多少项。 我有这个数据的结构。 我将如何为此创建格式?
通常你只需要在循环中单独调用 fscanf 来读取元素:
struct entry {
int data_size;
int *data;
char *name;
};
while (fscanf(input, "%d", &num) == 1) {
struct entry *e = malloc(sizeof *e);
e->data_size = num;
e->data = malloc(num * sizeof e->data[0]);
for (int i = 0; i < num; ++i) {
if (fscanf(input, " ,%d", &e->data[i]) != 1) {
fprintf(stderr, "Data format error\n");
exit(1); } }
if (fscanf(input, " ,%ms", &e->name) != 1) {
fprintf(stderr, "Data format error\n");
exit(1); }
// read a record into 'e' -- store it into a data structure somewhere
}
scanf
函数不支持可变数量的格式。 您需要根据元素的数量更改传递给函数的内容。
处理此问题的最佳方法是读取一行,然后使用strtok
将其拆分为标记,然后使用sscanf
解析出循环中的每个单独元素。
char line[100];
while (fgets(line, sizeof(line), fp)) {
int count, i;
int *array;
char *name, *p;
// read the count
p = strtok(line, ",");
sscanf(p, "%d", &count);
// allocate space for the array
array = malloc(count * sizeof(int));
// read each element
for (i=0; i<count; i++) {
p = strtok(NULL, ",");
sscanf(p, "%d", array + i);
}
// read the name
p = strtok(NULL, "\n");
name = strdup(p);
// do something with count, array, and name
}
请注意,这假设文件中的每一行格式正确,因此不会验证格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.