我正在尝试将文件内容按节读取到可用的结构中,“#”符号开始一个节,而“.”符号开始一个节。符号结束它。一个例子是:
# Type name
bird
mammal
.
# Type effectiveness
VeryEffective
NotEffective
.
到目前为止,我可以读取第一种类型的内容,但是当我尝试读取第二种类型的内容时,我会不断重新读取第一种类型的内容。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct
{
char types[1000];
char effectiveness[1000];
} sinFile;
sinFile record[1000];
FILE* file;
char line[121];
char period[10];
char Type2[20];
char* item;
char* item2;
int i = 0;
int j;
file = fopen("Test3.txt", "r");
while(fgets(line, 120, file)) {
item = strtok(line, " ");
strcpy(period, ".");
strcpy(Type2, "# Type effectiveness");
if (item[0] == '#' || item[0] == '.') {
continue;
} else {
do {
strcpy(record[i].types, line);
i++;
} while (strcmp(record[i].types, period) == 0);
}
for(j=0; strcmp(line, Type2) == 0; j++) {
do {
strcpy(record[j].effectiveness, line);
j++;
} while (strcmp(record[j].effectiveness, period)== 0);
}
}
fclose(file);
printf("%s", record[1].effectiveness);
}
目前,record[1].types 给出的结果与 record[1].effectness 相同;即“哺乳动物”。我觉得我已经很接近了,但我不知道如何继续。
最佳答案
这段代码有很多问题。为了让它工作,应该使用类似这个示例的东西。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
typedef struct
{
char types[1000];
char effectiveness[1000];
} sinFile;
sinFile record[1000];
FILE* file;
char line[121];
char* bp;
int i=0, j=0;
int state=0;
file = fopen("Test3.txt", "r");
while(fgets(line, 120, file)) {
for(bp=line;isspace(*bp);bp++);
if(state==0) {
if(*bp=='#') {
for(bp=line;isspace(*bp);bp++);
item = bp;
if(!strcmp(item,"Type name")) state=1;
else if(!strcmp(item,"Type effectiveness")) state=2;
}
}
else {
if(*bp=='.') {
state=0;
}
else if(state==1) {
strcpy(record[i].types, bp);
i++;
}
else if(state==2) {
strcpy(record[j].effectiveness, bp);
j++;
}
}
}
fclose(file);
printf("%s", record[1].effectiveness);
}
但是使用这段代码,第一个 block 中的行必须与第二个 block 中的行相对应...使用没有 block 的键/值对会更简单。
关于c - 逐节读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261895/