Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read specifically formatted data from a file?

Tags:

c

scanf

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

like image 667
marr Avatar asked Jan 21 '23 18:01

marr


2 Answers

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.

like image 150
Jeff Mercado Avatar answered Jan 29 '23 14:01

Jeff Mercado


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
like image 40
P M Avatar answered Jan 29 '23 15:01

P M