fgets() reads a line from a text stream into a bounded buffer. It is a simple way to process text or CSV files line by line without reading past the array capacity.
The original Plus2net example uses a sample CSV file. You can still download the sample test.csv file.
#include <stdio.h>
int main(void) {
FILE *file = fopen("test.csv", "r");
char line[128];
if (file == NULL) {
perror("test.csv");
return 1;
}
while (fgets(line, sizeof line, file) != NULL) {
fputs(line, stdout);
}
fclose(file);
return 0;
}
Key change: use one if instead of a loop when only the first line is required.
if (fgets(line, sizeof line, file) != NULL) {
fputs(line, stdout);
}
A common mistake is to loop on !feof(file). End-of-file is reported only after an attempted read reaches the end. Prefer testing the read operation itself:
while (fgets(line, sizeof line, file) != NULL) {
/* process line */
}
#include <stdio.h>
int main(void) {
FILE *file = fopen("missing.txt", "r");
if (file == NULL) {
perror("missing.txt");
return 1;
}
fclose(file);
return 0;
}
#include <stdio.h>
int main(void) {
FILE *file = fopen("products.txt", "r");
int id;
double price;
if (file == NULL) {
perror("products.txt");
return 1;
}
while (fscanf(file, "%d %lf", &id, &price) == 2) {
printf("Product ID: %d, Price: %.2f\n", id, price);
}
fclose(file);
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.