fputs() fgets() in C
×


fputs() fgets() in C

362

fputs() in C 

Description:

The fputs() function in C is used to write a string to a file specified by the stream.

Syntax of fputs():

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

str is a pointer to the null-terminated string for writing, while stream is a pointer to the FILE object indicating the file stream.

Return Value:

On success, fputs() returns a non-negative value.

On failure, it returns EOF.

Example:

#include<stdio.h>

int main() {
    FILE *fp;
    
    // Open a file named "output.txt" in write mode
    fp = fopen("output.txt", "w");
    
    // Check if the file opened successfully
    if (fp != NULL) {
        fputs("Hello, World!\n", fp);
        
        // Close the file
        fclose(fp);
        
        printf("String written to file successfully.\n");
    } else {
        printf("Error opening file.\n");
    }
    
    return 0;
}
Output:

Error opening file.

fgets()

Description:

The fgets() function in C is used to read a line from a file specified by the stream.

Syntax of fgets():

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

str: Pointer to the character array where the read line will be stored.

n: Maximum number of characters to read (including the null-terminator).

stream is a pointer to the FILE object that points to the file stream.

Return Value:

On success, fgets() returns str.

On reaching the end-of-file, it returns NULL.

On failure, it returns NULL.

Example:

#include<stdio.h> 

int main() {
    FILE *fp;
    char buffer[50];
    
    // Open a file named "input.txt" in read mode
    fp = fopen("input.txt", "r");
    
    // Check if the file opened successfully
    if (fp != NULL) {
        // Read a line from the file
        if (fgets(buffer, sizeof(buffer), fp) != NULL) {
            printf("Read from file: %s", buffer);
        } else {
            printf("Error reading from file.\n");
        }
        
        // Close the file
        fclose(fp);
    } else {
        printf("Error opening file.\n");
    }
    
    return 0;
}

Output:

Error opening file.

In these examples:

fputs("Hello, World!\n", fp) writes the string "Hello, World!" followed by a newline to the file.

fgets(buffer, sizeof(buffer), fp) reads a line from the file into the buffer character array.

These functions demonstrate string-based file operations using fputs() and fgets() in C.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments