#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,gender
1,John Deo,Four,75,female
2,Max Ruin,Three,85,male
3,Arnold,Three,55,male
------
------
------
if(fgets(str,50,fpt)){
puts(str);
}
Output
id,name,class,mark,gender
#include <stdio.h>
int main() {
FILE *file;
char line[100];
file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (!feof(file)) {
if (fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
}
fclose(file);
return 0;
}
This example demonstrates how to read a text file line by line using fgets().
#include <stdio.h>
int main() {
FILE *file;
char line[256];
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}
Output:
This is the content of example.txt file.
Each line will be printed until the end of the file.
---
This example shows how to handle errors when trying to open a file.
#include <stdio.h>
int main() {
FILE *file;
file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fclose(file);
return 0;
}
Output:
Error opening file: No such file or directory
---
This example reads numerical data from a file into variables using fscanf().
#include <stdio.h>
int main() {
FILE *file;
int num;
float price;
file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fscanf(file, "%d %f", &num, &price) == 2) {
printf("Product ID: %d, Price: %.2f\n", num, price);
}
fclose(file);
return 0;
}
Output:
Product ID: 101, Price: 25.99
Product ID: 102, Price: 15.75