简体   繁体   中英

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. I tried with fscanf but have no idea how to ignore the ":" and seperate the string ' 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. Below I use sscanf() instead just to illustrate without having to create a file. You can change the call to use fscanf() for your file.

#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

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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