How to read formatted data from a file?

I have to read the 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 that I am not allowed to use fgets. I tried with fscanf, but have no idea how to ignore the ":" and split the string name: "john".

+3
source share
2 answers

If you know for sure that the input file will be in a well-formed, very specific format, fscanf()it is always an option and will do most of the work for you. Below I use sscanf()instead just for illustration without the need 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

, , , - fgets() . , . , strtok() .

+6

, , ?

#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
+1

Source: https://habr.com/ru/post/1785393/


All Articles