The Wayback Machine - https://web.archive.org/web/20241129131805/https://www.geeksforgeeks.org/c-fopen-function-with-examples/
Open In App

C fopen() function with Examples

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing, etc. along with various modes. If the file exists then the fopen() function opens the particular file else a new file is created.

Syntax

The syntax of C fopen() is:

FILE *fopen(const char *file_name, const char *mode_of_operation);

Parameters

The method accepts two parameters of character pointer type:

  • file_name: This is of C string type and accepts the name of the file that is needed to be opened.
  • mode_of_operation: This is also of C string type and refers to the mode of the file access.

The below table lists valid mode_of_operation values in C with their meaning:

Opening Modes

Description

r

Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the first character in it. If the file cannot be opened fopen() returns NULL.

w

Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).

a

Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at the end of the file).

r+

Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer that points to the first character in it. Returns NULL, if unable to open the file.

w+

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.

a+

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at the end of the file).

rb

Open the binary file in read mode. If the file does not exist, the open() function returns NULL.

wb

Open the binary file in write mode. As the pointer is set to the start of the file, the contents are overwritten. If the file does not exist, a new file is created.

ab

Open the binary file in append mode. The file pointer is set after the last character in the file. A new file is created if no file exists with the name.

rb+

Open the binary file in read and write mode. If the file does not exist, the open() function returns NULL.

wb+

Open the binary file in read and write mode. Contents are overwritten if the file exists. It will be created if the file does not exist.

ab+

Open the binary file in read and append mode. A file will be created if the file does not exist.

Return Value

  • The function is used to return a pointer to FILE if the execution succeeds else NULL is returned. 

For a deeper dive into file handling in C, our C programming course offers step-by-step tutorials on reading from and writing to files, ensuring you master file operations.

Example of fopen()

C
// C program to illustrate fopen()

#include <stdio.h>
#include <stdlib.h>

int main()
{

    // pointer demo to FILE
    FILE* demo;

    // Creates a file "demo_file"
    // with file access as write-plus mode
    demo = fopen("demo_file.txt", "w+");

    // adds content to the file
    fprintf(demo, "%s %s %s", "Welcome", "to",
            "GeeksforGeeks");

    // closes the file pointed by demo
    fclose(demo);

    return 0;
}


On running the following command, a new file will be created by the name “demo_file.txt” with the following content: 

Welcome to GeeksforGeeks

Now if we wish to look into the file then we need to run the following code, which will open the file and display its content.

C
// C program to illustrate fopen()

#include <stdio.h>

int main()
{

    // pointer demo to FILE
    FILE* demo;
    int display;

    // Creates a file "demo_file"
    // with file access as read mode
    demo = fopen("demo_file.txt", "r");

    // loop to extract every characters
    while (1) {
        // reading file
        display = fgetc(demo);

        // end of file indicator
        if (feof(demo))
            break;

        // displaying every characters
        printf("%c", display);
    }

    // closes the file pointed by demo
    fclose(demo);

    return 0;
}


Output

Welcome to GeeksforGeeks

More articles on File Handling in C:

  1. Basics of File Handling in C
  2. fopen() for an existing file in write mode
  3. EOF, getc() and feof() in C
  4. File opening modes(r versus r+)


Previous Article
Next Article

Similar Reads

fopen() for an existing file in write mode
In C, fopen() is used to open a file in different modes. To open a file in write mode, "w" is specified. When mode "w" is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the
2 min read
btowc() function in C/C++ with Examples
The btowc() is a built-in function in C/C++ which converts a character to its wide character equivalent. It is defined within the cwchar header file of C++. Syntax: wint_t btowc( int ch ); Parameter:The function accepts a single mandatory parameter ch which specifies the single byte character to convert to it's wide character. Return Value: The fun
2 min read
wcsspn() function in C/C++ with Examples
The wcsspn() is a built-in function in C/C++ which returns the length of maximum initial segment of the wide string that consists of characters present in another wide string. It is defined within the cwchar header file of C++. Syntax: wcsspn(des, src) Parameters:The function accepts two mandatory parameters as described below. des: specifies to a
2 min read
getdate() and setdate() function in C with Examples
setdate() Method: getdate() function is defined in dos.h header file. This function fills the date structure *dt with the system's current date. Syntax struct date dt; getdate(&dt); Parameter: This function accepts a single parameter dt which is the object of structure date. Return Value: This method does not return anything. It just gets the s
2 min read
showbits( ) Function in C with Examples
Bitwise operators are operators (just like +, *, &&, etc.) that operate on ints and units at the binary level. This means they look directly at the binary digits or bits of an integer. This all sounds scary, but in truth, bitwise operators are quite easy to use and also quite useful! It is important, though, that you have an understanding o
4 min read
pthread_getcpuclockid() function in C with Examples
The pthread_getcpuclockid() function returns the clock ID of the CPU-time clock from a specified thread. Syntax: int pthread_getcpuclockid (pthread_t id, clockid_t* clock_id); Parameters: This method accepts following parameters: thread: The ID of the thread that you want to get the clock ID for, which you can get when you call pthread_create() or
3 min read
free() Function in C Library With Examples
The free() function in C is used to free or deallocate the dynamically allocated memory and helps in reducing memory wastage. The C free() function cannot be used to free the statically allocated memory (e.g., local variables) or memory allocated on the stack. It can only be used to deallocate the heap memory previously allocated using malloc(), ca
3 min read
C Function Arguments and Function Return Values
Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function
6 min read
Logical Not ! operator in C with Examples
! is a type of Logical Operator and is read as "NOT" or "Logical NOT". This operator is used to perform "logical NOT" operation, i.e. the function similar to Inverter gate in digital electronics. Syntax: !Condition // returns true if the conditions is false // else returns false Below is an example to demonstrate ! operator: Example: // C program t
1 min read
iswprint() in C/C++ with Examples
The iswprint() is a built-in function in C/C++ which checks if the given wide character can be printed or not. It is defined within the cwctype header file of C++. By default, the following characters are printable: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&'()*+, -./:;?@[\]^_`{|}~)Space Sy
2 min read
iswgraph() in C/C++ with Examples
The iswgraph() is a built-in function in C/C++ which checks if the given wide character has a graphical representation or not. It is defined within the cwctype header file of C++. By default, the following characters are graphic: Digits (0 to 9)Uppercase letters (A to Z)Lowercase letters (a to z)Punctuation characters (!"#$%&'()*+, -./:;?@[\]^_
2 min read
mbrtoc16() in C/C++ with Examples
The mbrtoc16() is a built-in function in C/C++ which converts a narrow multibyte character to a 16 bit character representation. It is defined within the uchar.h header file of C++. Syntax: ssize_t mbrtoc16( char16_t* pc16, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below:
3 min read
mbrtoc32() in C/C++ with Examples
The mbrtoc32() is a built-in function in C/C++ which converts a narrow multibyte character to a 32 bit character representation. It is defined within the uchar.h header file of C++. Syntax: size_t mbrtoc32( char32_t* pc32, const char* s, size_t n, mbstate_t* ps); Parameters: The function accepts four mandatory parameter which are described below: s
3 min read
wmemset() in C/C++ with Examples
The wmemset() function is a builtin function in C/C++ which copies a single wide character for a specified number of time to a wide character array. It is defined within the cwchar header file in C++. Syntax: wmemset(des, ch, count) Parameters: The function accepts three parameters which are described below. des: It specifies to the wide character
2 min read
cauchy_distribution a() in C++ with Examples
The cauchy_distribution::a() function is an inbuilt function in C++ STL which is used to returns the distribution parameter associated with Cauchy distribution. The class cauchy_distribution is present in header file random. Before going to the syntax of the function, brief introduction to Cauchy Distribution. Cauchy Distribution A random variable
2 min read
asctime() and asctime_s() functions in C with Examples
asctime() function The asctime() function returns the pointer to the string that contains the information stored in the structure of the struct tm type. This function is used to return the local time defined by the system in string format. This function is defined in <time.h> header file. Syntaxchar *asctime(const struct tm* tm_ptr);Parameter
3 min read
ctype.h(<cctype>) library in C/C++ with Examples
As string.h header file contains inbuilt functions to handle Strings in C/C++, the ctype.h/<cctype> contains inbuilt functions to handle characters in C/C++ respectively. Characters are of two types: Printable Characters: The characters that are displayed on the terminal. Control Characters: The characters that are initiated to perform a spec
5 min read
<cfloat> float.h in C/C++ with Examples
This header file consists of platform-dependent and implementation specific floating point values. A floating point has four parts. Sign Its value can be either negative or non-negative. Base It is also known as radix of exponent representation which represents different numbers with single number i.e. 2 for binary, 10 for decimal, 16 for hexadecim
4 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
Implicit Type Conversion in C with Examples
Prerequisite: Data Types, Type Conversion Implicit Type Conversion is also known as 'automatic type conversion'. It is done by the compiler on its own, without any external trigger from the user. It generally takes place when in an expression more than one data type is present. In such condition type conversion (type promotion) takes place to avoid
5 min read
Difference between Argument and Parameter in C/C++ with Examples
Argument An argument is referred to the values that are passed within a function when the function is called. These values are generally the source of the function that require the arguments during the process of execution. These values are assigned to the variables in the definition of the function that is called. The type of the values passed in
4 min read
Nested Loops in C with Examples
A nested loop means a loop statement inside another loop statement. That is why nested loops are also called "loop inside loops". We can define any number of loops inside another loop. 1. Nested for Loop Nested for loop refers to any type of loop that is defined inside a 'for' loop. Below is the equivalent flow diagram for nested 'for' loops: Synta
5 min read
Predefined Macros in C with Examples
According to C89 Standard, C programming language has following predefined macros: __LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler fin
4 min read
exit(0) vs exit(1) in C/C++ with Examples
exit is a jump statement in C/C++ language which takes an integer (zero or non zero) to represent different exit status. There are two types of exit status in C/C++: Exit Success: Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt. #include
2 min read
Jagged Array or Array of Arrays in C with Examples
Prerequisite: Arrays in C Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays. Example: arr[][] = { {0, 1, 2}, {6, 4}, {1, 7, 6, 8, 9}, {5} }; Below are the methods to implement the j
3 min read
fpclassify() method in C/C++ with Examples
The fpclassify() function are defined in header math.h header in C and cmath library in C++. This function is used to get the value of type int that matches one of the classification macro constants (depending on the value of x). Syntax: int fpclassify(int x); int fpclassify(float x); int fpclassify(double x); int fpclassify(long double x); Paramet
2 min read
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 min read
tgamma() method in C/C++ with Examples
The tgamma() function is defined in header math.h header in C and cmath library in C++. This function is used to compute the gamma function of an argument passed to the function. Syntax of tgamma()float tgamma(float x); double tgamma(double x); long double tgamma(long double x);Parameters x: The value whose gamma function is to be computed. It can
3 min read
Strict Aliasing Rule in C with Examples
Aliasing: Aliasing refers to the situation where the same memory location can be accessed using different names. For Example, if a function takes two pointers A and B which have the same value, then the name A[0] aliases the name B[0] i.e., we say the pointers A and B alias each other. Below is the program to illustrate aliasing in C: C/C++ Code //
4 min read
Finite and Infinite Recursion with examples
The process in which a function calls itself directly or indirectly is called Recursion and the corresponding function is called a Recursive function. Using Recursion, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS, etc. Types of Recursions: Recursion
6 min read
three90RightbarBannerImg