// projects.c-language
10 Best C Language Projects
Hand-picked and ordered easiest → hardest — each with complete code and expected output. Build these to turn lessons into a portfolio.
Back to C Language course
// solution.code
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_LINE 1024
int main() {
// Create a sample text file for demonstration
FILE *sample = fopen("sample.txt", "w");
fprintf(sample, "Hello World!\nThis is a test file.\nIt has multiple lines.\n");
fclose(sample);
FILE *file = fopen("sample.txt", "r");
if (!file) {
printf("Error opening file\n");
return 1;
}
int lines = 0, words = 0, chars = 0;
int freq[256] = {0}; // Character frequency array
char line[MAX_LINE];
// Read file line by line
while (fgets(line, MAX_LINE, file)) {
lines++;
chars += strlen(line);
// Count characters frequency
for (int i = 0; line[i]; i++) {
freq[(unsigned char)line[i]]++;
}
// Count words (space-separated tokens)
int in_word = 0;
for (int i = 0; line[i]; i++) {
if (isspace(line[i])) {
in_word = 0;
} else if (!in_word) {
in_word = 1;
words++;
}
}
}
fclose(file);
// Display statistics
printf("=== Text File Statistics ===\n");
printf("Lines: %d\n", lines);
printf("Words: %d\n", words);
printf("Characters: %d\n\n", chars);
printf("Top 5 Character Frequencies:\n");
// Simple bubble sort to find top 5
for (int k = 0; k < 5; k++) {
int max_idx = 0;
for (int i = 1; i < 256; i++) {
if (freq[i] > freq[max_idx]) {
max_idx = i;
}
}
if (freq[max_idx] > 0) {
if (isprint(max_idx)) {
printf("'%c': %d\n", max_idx, freq[max_idx]);
} else {
printf("(ASCII %d): %d\n", max_idx, freq[max_idx]);
}
freq[max_idx] = 0; // Remove from next search
}
}
return 0;
} output
=== Text File Statistics === Lines: 3 Words: 11 Characters: 56 Top 5 Character Frequencies: ' ': 9 'e': 5 'l': 5 'i': 4 's': 4
