Lesson 49: File I/O Part 3: Character I/O (fputc, fgetc)
These functions are used for reading or writing a single character to/from a file stream.
Writing a Character: fputc()
Writes a single character to the specified file stream.
Syntax: int fputc(int character, FILE *stream);
c FILE *fp = fopen("data.txt", "w");
if (fp != NULL) { fputc('A', fp); fputc('B', fp); fputc('\n', fp); fclose(fp); } // 'data.txt' now contains: A // B
Reading a Character: fgetc()
Reads the next character from the specified file stream. It returns the character read, or EOF (End Of File) if the end of the file is reached or an error occurs.
c FILE *fp = fopen("data.txt", "r"); int ch; // Use int to hold EOF
if (fp != NULL) { while ((ch = fgetc(fp)) != EOF) { printf("%c", (char)ch); // Cast back to char for printing } fclose(fp); }
Copying Files (Practical Example)
Combining fgetc and fputc allows us to create a function that copies the contents of one file to another, character by character.