如何从文件中读取特定格式的数据?
问题描述:
我应该从类似这种格式的文件读取输入和参数:如何从文件中读取特定格式的数据?
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()
都是不允许的。缓存比恕我直言总是容易。然后你可以使用strtok()
之类的其他函数以及不需要解析的东西。
答
也许这就是你想要的?
#include <stdio.h>
#include <string.h>
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
+0
不,我正在尝试提取John,Doe,2009等,并将它们存储在带有唯一ID的链接列表中。我对程序的其余部分没有任何问题,我只是无法弄清楚如何从文件中提取正确的字符串和整数。我应该使用其他的东西而不是scanf? – marr 2011-01-14 10:23:25
为什么你不允许使用fgets?这是一项家庭作业吗? – JeremyP 2011-01-14 10:43:30