Fopen() function in C
×


Fopen() function in C

37

The fopen() function in C is used to open a file.

It provides a way to interact with files, allowing programs to read from and write to them.

This function is part of the standard I/O library in C and is widely used in file handling operations.

Syntax of fopen() Function:

FILE *fopen(const char *filename, const char *mode);

Parameters:

The "filename" parameter is a character string that specifies the name of the file to be opened.

mode: A string containing the mode in which the file should be opened.

The mode can be "r" for reading, "w" for writing (truncate file to zero length or create a new file), "a" for appending (writing to the end of the file), "r+" for reading and writing, "w+" for reading and writing (truncate file to zero length or create a new file), and "a+" for reading and appending (writing to the end of the file).

Additionally, "b" can be added to any mode to open the file in binary mode (e.g., "rb", "wb", etc.).


Return Value:

If the file is successfully opened, fopen() returns a pointer to the FILE object associated with the opened file.

If an error occurs, fopen() returns NULL, indicating failure to open the file.

Example:

// program for fopen() in C
#include<stdio.h> 

int main() {
    FILE *fp;

    fp = fopen("example.txt", "w");

    // Check if the file is opened successfully
    if (fp != NULL) {
        printf("File opened successfully.\n");

        // Close the file
        fclose(fp);
    } else {
        printf("Error opening file.\n");
    }

    return 0;
}

Output:

File opened successfully.

In this example, the fopen() function is used to open a file named "example.txt" in write mode ("w").

If the file is opened successfully, a success message is printed, and the file is closed using fclose().

If an error occurs during file opening, an error message is displayed.



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