🔹 Exercise File Programming

 

🔹 Example Problem 1: Write to a File

✅ Using Built-in Functions

#include <stdio.h> int main() { FILE *fp; char text[100]; fp = fopen("output.txt", "w"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } printf("Enter a line of text: "); fgets(text, sizeof(text), stdin); // built-in function fputs(text, fp); // built-in function fclose(fp); printf("Data written successfully.\n"); return 0; }

🚀 Without Built-in String Functions (manual copy)

#include <stdio.h> int main() { FILE *fp; char text[100]; int i = 0; fp = fopen("output.txt", "w"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } printf("Enter a line of text: "); while ((text[i] = getchar()) != '\n' && i < 99) { // manual input i++; } text[i] = '\0'; // write manually character by character for (int j = 0; text[j] != '\0'; j++) { fputc(text[j], fp); } fclose(fp); printf("Data written successfully.\n"); return 0; }

🔹 Example Problem 2: Count Characters, Words, Lines

✅ Using Built-in Functions (isspace)

#include <stdio.h> #include <ctype.h> int main() { FILE *fp; char ch; int characters = 0, words = 0, lines = 0, inWord = 0; fp = fopen("output.txt", "r"); if (fp == NULL) { printf("File not found!\n"); return 1; } while ((ch = fgetc(fp)) != EOF) { characters++; if (ch == '\n') lines++; if (isspace(ch)) { // built-in function inWord = 0; } else if (!inWord) { inWord = 1; words++; } } fclose(fp); printf("Characters: %d\nWords: %d\nLines: %d\n", characters, words, lines); return 0; }

🚀 Without Built-in Functions (isspace replaced manually)

#include <stdio.h> int isSpace(char c) { // manual implementation return (c == ' ' || c == '\n' || c == '\t'); } int main() { FILE *fp; char ch; int characters = 0, words = 0, lines = 0, inWord = 0; fp = fopen("output.txt", "r"); if (fp == NULL) { printf("File not found!\n"); return 1; } while ((ch = fgetc(fp)) != EOF) { characters++; if (ch == '\n') lines++; if (isSpace(ch)) { // using custom function inWord = 0; } else if (!inWord) { inWord = 1; words++; } } fclose(fp); printf("Characters: %d\nWords: %d\nLines: %d\n", characters, words, lines); return 0; }

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ