Reading & Displaying each line from File
C Programming
File handling
We have one test.csv file having 35 rows of data. We will write one program to display each line of data inside a loop. You can download the sample test.csv file here.
#include <stdio.h>
int main(void){
FILE *fpt; // file pointer
char c,d;
char str[50];
fpt=fopen("test.csv","r"); // file already exit for reading
if(fpt==NULL)
printf("Can't open file ");
else {
while(fgets(str,50,fpt)){
puts(str);
}
}
fclose(fpt);
return 0;
}
Output is here.
id,name,class,mark,sex
1,John Deo,Four,75,female
2,Max Ruin,Three,85,male
3,Arnold,Three,55,male
------
------
------
Getting the first line of data
In the code by changing the while to if we will get one line of data only.
if(fgets(str,50,fpt)){
puts(str);
}
Output
id,name,class,mark,sex
← File Handling in C
This article is written by plus2net.com team.
plus2net.com