Help with reading a file in C, please.

I have a file with 190 lines, that goes something like this:

[code]Antigua,English,Local dialects
Costa Rica,Spanish,English
First field is the country, following fields are the different languages spoken in that country.
Since some countries have more languages than others, I am stuck trying to read the file using fgets() and sscanf().
I'm doing this:
while(i < SIZE && fgets(buffer, 255, fp))
sscanf(buffer, "%[^,]%*c%[^
]", holdName, buffer);//read the country first, and keep the rest for the languages

/* Here is where I'm lost, I want to read a language, keep the rest of the buffer to repeat until
the buffer is empty. But obviously I'm doing it wrong */
while(sscanf(buffer, "%[^,]%*c%[^
]", holdLang, buffer) != '

Any help please?
I have this big program to do, and can't do anything else until I am able to read the whole file.



  • [color=Blue]Better way would be to use fgets() to read one line of the file and then use strtok() to parse that line using comma separator.[/color]
  • Thanks a lot!
  • It's simple. Take a buffer say " char buf[] "
    and use the function,


    here in function "fread()"

    [b]buf[/b] -is where the contents of the file will be stored.
    [b]190[/b] -number of characters to read(190 in your case).
    [b]1 [/b] -number of items to read.
    [b]fp[/b] -file pointer pointing towards the file to be operated.
  • [color=Blue]This code will not work. 190 is approximate # of lines in file - not characters per line. And lines will not be the same length, so reading constantly by 190 characters will skip some short lines and lines will be loaded not from the beginning of each line, but from some place in file which is divisible by 190 bytes.[/color]
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!