Reading and Writing Text Files in C

Reading and writing text files in C programming involves using functions and file pointers to interact with the file's content.

Reading Text Files in C

Reading Line by Line (Using fgets)

fgets reads a line of text from a file, including the newline character. It's useful for processing text files line by line.

FILE* file = fopen("textfile.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } char buffer[100]; while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("%s", buffer); // Process the line } fclose(file);
Reading Character by Character (Using fgetc)

fgetc reads a single character from a text file, allowing character-level processing.

int c; FILE* file = fopen("textfile.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } while ((c = fgetc(file)) != EOF) { printf("%c", (char)c); // Process the character } fclose(file);

Writing to Text Files in C

Writing Line by Line (Using fprintf)

fprintf allows you to write formatted data to a text file, including strings, integers, and more.

FILE* file = fopen("output.txt", "w"); if (file == NULL) { perror("File opening failed"); return 1; } fprintf(file, "This is a line of text.\n"); fprintf(file, "Another line of text.\n"); fclose(file);
Writing Character by Character (Using fputc)

fputc writes a single character to a text file.

FILE* file = fopen("output.txt", "w"); if (file == NULL) { perror("File opening failed"); return 1; } char character = 'A'; while (character <= 'Z') { fputc(character, file); character++; } fclose(file);

Custom Formatted Output (Using fprintf)

You can manually create formatted data and write it to the file using fprintf.

FILE* file = fopen("data.txt", "w"); if (file == NULL) { perror("File opening failed"); return 1; } fprintf(file, "Name: %s, Age: %d\n", "John", 30); fprintf(file, "Name: %s, Age: %d\n", "Alice", 25); fclose(file);

Which method to use?

The best way to read and write text files depends on the specific needs of the program. If the program needs to process the data character-by-character, then character-by-character reading and writing should be used. If the program needs to process the data line-by-line, then line-by-line reading and writing should be used.

Conclusion

Reading and writing text files involves using functions like fgets and fprintf to interact with the content of the files. fgets is used to read text data line by line, while fprintf is employed for writing formatted text data to the file. Proper file handling, error checking, and formatting are key considerations when working with text files in C.