如何从文件中读取特定格式的数据?

我应该从类似于这种格式的文件中读取输入和参数:

Add id:324 name:"john" name2:"doe" num1:2009 num2:5 num2:20 

问题是我不允许使用fgets。 我尝试使用fscanf,但不知道如何忽略“:”并分隔字符串’name:“john”’。

如果您确定输入文件格式正确,格式非常具体,那么fscanf()始终是一个选项,它将为您完成大量工作。 下面我使用sscanf()代替只是为了说明而不必创建文件。 您可以更改调用以对文件使用fscanf()

 #define MAXSIZE 32 const char *line = "Add id:324 name:\"john\" name2:\"doe\" num1:2009 num2:5 num3:20"; char op[MAXSIZE], name[MAXSIZE], name2[MAXSIZE]; int id, num1, num2, num3; int count = sscanf(line, "%s " "id:%d " "name:\"%[^\"]\" " /* use "name:%s" if you want the quotes */ "name2:\"%[^\"]\" " "num1:%d " "num2:%d " "num3:%d ", /* typo? */ op, &id, name, name2, &num1, &num2, &num3); if (count == 7) printf("%s %d %s %s %d %d %d\n", op, id, name, name2, num1, num2, num3); else printf("error scanning line\n"); 

输出:

添加324 john doe 2009 5 20

否则,我会手动解析一次读取一个字符的输入,或者如果出于任何原因使用fgets()不允许,则将其fgets()缓冲区。 让它缓冲比恕我直言更容易。 然后你可以使用其他函数,如strtok()和诸如此类的解析。

也许这就是你想要的?

 #include  #include  int main() { char str[200]; FILE *fp; fp = fopen("test.txt", "r"); while(fscanf(fp, "%s", str) == 1) { char* where = strchr( str, ':'); if(where != NULL ) { printf(" ':' found at postion %d in string %s\n", where-str+1, str); }else { printf("COMMAND : %s\n", str); } } fclose(fp); return 0; } 

如果输出它

 COMMAND : Add ':' found at postion 3 in string id:324 ':' found at postion 5 in string name:"john" ':' found at postion 6 in string name2:"doe" ':' found at postion 5 in string num1:2009 ':' found at postion 5 in string num2:5 ':' found at postion 5 in string num2:20