简体   繁体   English

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

[英]How to read specifically formatted data from a file?

I'm supposed to read inputs and arguments from a file similar to this format: 我应该从类似于这种格式的文件中读取输入和参数:

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

The problem is I'm not allowed to use fgets. 问题是我不允许使用fgets。 I tried with fscanf but have no idea how to ignore the ":" and seperate the string ' name:"john" '. 我尝试使用fscanf,但不知道如何忽略“:”并分隔字符串'name:“john”'。

If you know for sure the input file will be in a well-formed, very specific format, fscanf() is always an option and will do a lot of the work for you. 如果您确定输入文件将是格式良好,非常特定的格式, fscanf()始终是一个选项,并将为您完成大量工作。 Below I use sscanf() instead just to illustrate without having to create a file. 下面我使用sscanf()代替只是为了说明而不必创建文件。 You can change the call to use fscanf() for your file. 您可以更改调用以使用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");

Outputs: 输出:

Add 324 john doe 2009 5 20 添加324 john doe 2009 5 20

Otherwise, I would manually parse the input reading a character at a time or or throw it in a buffer if for whatever reason using fgets() wasn't allowed. 否则,我会手动解析一次读取一个字符的输入,或者如果出于任何原因使用fgets()不允许,则将其fgets()缓冲区。 It's always easier to have it buffered than not IMHO. 让它缓冲比恕我直言更容易。 Then you could use other functions like strtok() and whatnot to do the parse. 然后你可以使用其他函数,如strtok()和诸如此类的解析。

perhaps this is what you want ? 也许这就是你想要的?

#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;
}

If output of it will be 如果输出它

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM