How to read specifically formatted data from a file?

前端 未结 2 691
野的像风
野的像风 2021-01-19 06:30

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
相关标签:
2条回答
  • 2021-01-19 07:07

    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
    
    0 讨论(0)
  • 2021-01-19 07:18

    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.

    0 讨论(0)
提交回复
热议问题