How to use scanf \ fscanf to read a string and analyze for variables?

I am trying to read a text file built with the following format on each line:

char *, char *, int

i.e:.

aaaaa, dfdsd, 23

bbbasdaa, ddd, 100

I want to use fscanf to read a string from a file and automatically parse the string in varilables string1, string2, intA

What is the right way to do this? Thanks

+4
source share
2 answers

Assuming you have:

char string1[20]; char string1[20]; int intA; 

You can do:

 fscanf(file, "%19[^,],%19[^,],%d\n", string1, string2, &intA); 

%[^,] reads a string of decimal places and stops at the first comma. 19 - the maximum number of characters to read (provided that the buffer size is 20) so that you do not have a buffer overflow.

+6
source

If you really cannot make any safe assumption about the length of the string, you should use getline (). This function takes three arguments: a pointer to a string (char **), a pointer to an int containing the size of this string and a pointer to a file, and returns the length of the string. getline () dynamically allocates space for the string (using malloc / realloc), and therefore you do not need to know the length of the string and the buffer overflow. Of course, this is not as convenient 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); 
0
source

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


All Articles