fputs() in C - Source Code Example

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

fputs() Function Overview

The fputs() function in C writes a string to a file. It's simple and works well for writing lines of text.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char data[] = "Hello, Ram! How's it going?";

    // Open a file for writing
    filePtr = fopen("sample.txt", "w");
    if (filePtr == NULL) {
        printf("Couldn't open the file.\n");
        return 1;
    }

    // Write the string to the file
    if (fputs(data, filePtr) == EOF) {
        printf("Had trouble writing to the file.\n");
        return 2;
    }

    // Close the file
    fclose(filePtr);
    printf("Written to the file.\n");

    return 0;
}

Output

Written to the file.

Explanation

1. Open a file named "sample.txt" to write.

2. Write a string to the file with fputs().

3. If there's an error, print an error message.

4. Close the file after writing.

5. Print a message if the write is successful.


Comments