fputc() in C - Source Code Example

In this source code example, we will see how to use the fputc() function in C programming with an example.

fputc() Function Overview

The fputc() function in C lets you write a single character to a file. It's like using a pencil to write one letter in a book.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char text[] = "Hello, Ram!";
    int i;

    // Opening a sample file for writing
    filePtr = fopen("sample.txt", "w");
    if (!filePtr) {
        printf("Error opening the file.\n");
        return 1;
    }

    // Writing to the file using fputc
    for (i = 0; text[i]; i++) {
        fputc(text[i], filePtr);
    }

    // Adding a newline using fputc
    fputc('\n', filePtr);

    // Writing a single char to the file
    fputc('A', filePtr);

    // Always shut the file when done
    fclose(filePtr);

    // Let's confirm by reading the file and displaying the content
    filePtr = fopen("sample.txt", "r");
    if (!filePtr) {
        printf("Error opening the file.\n");
        return 1;
    }

    printf("File content:\n");
    char ch;
    while ((ch = fgetc(filePtr)) != EOF) {
        putchar(ch);
    }

    fclose(filePtr);
    return 0;
}

Output

File content:
Hello, Ram!
A

Explanation

1. We open a file named "sample.txt" for writing.

2. Using a loop, we go through each character of the "Hello, Ram!" string and write it to the file using fputc().

3. We then add a new line to the file using fputc().

4. Next, we write a single character 'A' to the file.

5. After writing, we close the file.

6. To make sure our writing went well, we open the file again, this time for reading, and show its contents.

With fputc(), we can simply and precisely control which characters to write to a file.


Comments