How to use scanf \ fscanf to read a line and parse into variables?
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,ddd,100
i want to use fscanf to read a line from file, and automatically parse the line into the varilables string1,string2,intA
What's the correct 开发者_StackOverflowway of doing it ? Thanks
Assuming you have:
char string1[20];
char string1[20];
int intA;
you could do:
fscanf(file, "%19[^,],%19[^,],%d\n", string1, string2, &intA);
%[^,]
reads a string of non-comma characters and stops at the first comma. 19
is the maximum number of characters to read (assuming a buffer size of 20) so that you don't have buffer overflows.
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);
精彩评论