4

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 way of doing it ? Thanks

Community
  • 1
  • 1
RanH
  • 740
  • 1
  • 11
  • 31

2 Answers2

7

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.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • 1
    What if i don't know the (max)length of a string ? Must i define some maximum length no matter what ? – RanH Mar 05 '11 at 16:13
  • 2
    Yup. Welcome to the joy of C-style string manipulation. The "correct" answer is to use something akin to C++'s std::string. The "lazy" answer is the ever popular char foo[1000]. – ChrisV Mar 05 '11 at 16:54
0

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);
sl0815
  • 567
  • 1
  • 9
  • 21