Nadav
Nadav

Reputation: 2717

Reading from a file

hello i got a problem with reading from a file, i am trying to read from a file using fscanf() and i cant seem to sort it out. i try to read the file line by line and putting the string in a variable (buffer) each time but i cant understand how the while loop is suppose to be looking like thanks in advance

the file that i want to read from is a txt file with this format: first line :"1234,abc,etc" second line : "2432,fjh,etc" and more lines like those i want to be able to use the fscanf method inorder to put in each loop the all line lets say "1234,abc,etc" in my string variable and so on till i dont have any more lines to read from

this is what i managed to gather so far (ofc its not the currect way to write it):

char* buffer[100]; 
while (fscanf(FILE *finput,"%s",buffer)!=something) 
{ 
    printf("%s",buffer); 
}

i want this code to be able to print all of the lines in my code if you would be able to correct my errors i will greatly appriciate it

Upvotes: 1

Views: 585

Answers (1)

karlphillip
karlphillip

Reputation: 93410

I feel like you should read some of these great topics first:

Trouble reading a line using fscanf()

Reading file using fscanf() in C

fscanf multiple lines [c++]

There are plenty of reasons why you should use fgets or something else instead.

Quoting from this place:

fscanf() is a field oriented function and is inappropriate for use in a robust, general-purpose text file reader. It has two major drawbacks:

  • You must know the exact data layout of the input file in advance and rewrite the function call for every different layout.
  • It's difficult to read text strings that contain spaces because fscanf() sees space characters as field delimiters.

If you know the size of file you're trying to read, you could use fread(), which is block oriented.

Upvotes: 3

Related Questions