READING FROM A FILE IN C! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

READING FROM A FILE IN C!

Hi. I have a problem in understanding how to read a file and copy what i'm reading to an array or matrix. For example ,I have in a file : 324; 213; 231; 912 ( the integers are separated by " ; " and a space). I want to copy that into an array of integers, I know that I can do it with fscanf() function , but i don't know how. I thought about writing fscanf(filepointer, "%d; %d; %d; %d", 4 int variables); but is this correct? Would it just skip the ";" and the spaces (in the fscanf i wrote ";space" after %d) And what if there were more than 4 integers , like 100 , i shouldn't do it manually : would it become something like this : (if my prediction was correct) int a[100]; int i; for(i=0;i<100;i++) { fscanf(filepointer,"%d; ",a[i]); } Thank you so much and have a nice day!

10th Feb 2020, 3:02 PM
Andrei Boboc
Andrei Boboc - avatar
3 Answers
+ 3
i suggest doing it like this int a[1000]; int i = 0; while (!feof(fptr)){ fscanf(fptr, "%d; ", &a[i]); i++; } if the amount of integers is unknown then it's better using feof to keep scanning until the end of file is reached. and finally the integer i, would represent the number of integers on the file
10th Feb 2020, 8:43 PM
Shen Bapiro
Shen Bapiro - avatar
+ 3
I recommend you to refer this website, https://overiq.com/c-programming-101/fscanf-function-in-c/
10th Feb 2020, 3:16 PM
Akshay Harshora
Akshay Harshora - avatar
0
I got it, thank both of you very much.
11th Feb 2020, 10:16 AM
Andrei Boboc
Andrei Boboc - avatar