fputs() and fgets() in C

In C, the functions fputs() and fgets() are used for handling string-based input and output operations in files. They are part of the C standard library and provide a convenient way to interact with text data in files.

fputs()

The fputs() function is used to write a string to a file. It writes the string to the specified file, excluding the null terminator, and it does not add a newline character automatically.

Syntax

                            
int fputs(const char *str, FILE *stream);
                            
                        

The function returns a non-negative value on success and EOF on error.

Example: Using fputs()

                            
#include <stdio.h>
int main() 
{
    FILE *file = fopen("example.txt", "w");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    fputs("Hello, world!", file);              
            
    fclose(file);
    return 0;
}
                            
                        

Output:

The string "Hello, world!" is written to the "example.txt" file.

fgets()

The fgets() function is used to read a string from a file. It reads up to a specified number of characters, including the newline character if encountered, and stores the result in the provided buffer.

Syntax

                            
char *fgets(char *str, int n, FILE *stream);
                        
                        

The function returns the string on success or NULL if an error occurs or the end of the file is reached.

Example: Using fgets()

                            
#include <stdio.h>
int main()
{
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file\n");
        return 1;
    }

    char buffer[100];
    if (fgets(buffer, sizeof(buffer), file) != NULL) {
        printf("Read: %s\n", buffer);
    }             
            
    fclose(file);
    return 0;            
}
                        
                        

Output:

Read: Hello, world! (The string is read from the "example.txt" file and displayed on the console).

Difference Between fputs() and fgets()

Aspect fputs() fgets()
Function Purpose Writes a string to a file. Reads a string from a file.
Return Value Returns a non-negative value or EOF on error. Returns the string or NULL on error or end of file.
Usage Used for writing strings to files. Used for reading strings from files.

Key Points