Character-by-character file reading can be used to count spaces, line breaks or other characters. Store the return value of fgetc() in an int so that EOF can be detected correctly.
#include <stdio.h>
int main(void) {
FILE *file = fopen("data2.txt", "r");
if (file == NULL) {
perror("data2.txt");
return 1;
}
int ch;
unsigned long line_breaks = 0;
unsigned long spaces = 0;
while ((ch = fgetc(file)) != EOF) {
if (ch == '\n') {
line_breaks++;
}
if (ch == ' ') {
spaces++;
}
}
if (ferror(file)) {
printf("An error occurred while reading the file.\n");
fclose(file);
return 1;
}
fclose(file);
printf("Line breaks: %lu\n", line_breaks);
printf("Spaces: %lu\n", spaces);
return 0;
}
welcome to plus2net
Next Line
Key change: compare every byte with the character you want to count.
#include <stdio.h>
int main(void) {
FILE *file = fopen("data2.txt", "r");
const int target = 'e';
unsigned long count = 0;
if (file == NULL) {
perror("data2.txt");
return 1;
}
int ch;
while ((ch = fgetc(file)) != EOF) {
if (ch == target) {
count++;
}
}
fclose(file);
printf("Occurrences of '%c': %lu\n", target, count);
return 0;
}
The earlier page stored the file character in char and tested that variable against EOF. That can fail because EOF is an int value outside the range needed for ordinary unsigned byte values. Use:
int ch;
while ((ch = fgetc(file)) != EOF) {
/* process ch */
}
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.