How to use scanf \ fscanf to read a line and parse into variables?

前端 未结 2 1093
天命终不由人
天命终不由人 2021-01-03 06:39

I\'m trying to read a text file built with the following format in every line:

char*,char*,int

i.e.:

aaaaa,dfdsd,23

bbbasdaa,ffffd,100

2条回答
  •  天涯浪人
    2021-01-03 07:02

    If you really cannot make any safe assumption about the length of a line, you should use getline(). This function takes three arguments: a pointer to a string (char**), a pointer to an int holding the size of that string and a file pointer and returns the length of the line read. getline() dynamically allocates space for the string (using malloc / realloc) and thus you do not need to know the length of the line and there are no buffer overruns. Of course, it is not as handy as fscanf, because you have to split the line manually.

    Example:

    char **line=NULL;
    int n=0,len;
    FILE *f=fopen("...","r");
    
    if((len=getline(&line,&n,f)>0)
    {
    ...
    }
    
    free(line);
    fclose(f);
    

提交回复
热议问题