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

C fopen() function with Examples

Last Updated : 23 Jun, 2023
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. 

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(&amp;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
fill_n() function in C++ STL with examples
The fill_n() function in C++ STL is used to fill some default values in a container. The fill_n() function is used to fill values upto first n positions from a starting position. It accepts an iterator begin and the number of positions n as arguments and fills the first n position starting from the position pointed by begin with the given value. Sy
2 min read
showbits( ) Function in C with Examples
Bitwise operators are operators (just like +, *, &amp;&amp;, 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
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Deep, Shallow and Lazy Copy with Java Examples
In object-oriented programming, object copying is creating a copy of an existing object, the resulting object is called an object copy or simply copy of the original object.There are several ways to copy an object, most commonly by a copy constructor or cloning.We can define Cloning as "create a copy of object". Shallow, deep and lazy copy is relat
4 min read
Java Math min() method with Examples
The Java.lang.math.min() function is an inbuilt function in java that returns the minimum of two numbers. The arguments are taken in int, double, float and long. If a negative and a positive number is passed as an argument then the negative result is generated. And if both parameters passed are negative then the number with the higher magnitude is
2 min read
IntStream findAny() with examples
IntStream findAny() returns an OptionalInt (a container object which may or may not contain a non-null value) describing some element of the stream, or an empty OptionalInt if the stream is empty. Syntax : OptionalInt findAny() Where, OptionalInt is a container object which may or may not contain a non-null value and the function returns an Optiona
2 min read
uniq command in Linux with examples
The linux uniq command is basically used to remove all repeated lines in a file. This command is used when a line is repeated multiple times and replace these multiple lines with one line. This command is designed to work on sorted files. Purpose : Remove repetitious lines from the sorted 'input-file' and send unique lines to the 'output-file'. If
2 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
IntStream empty() in Java with examples
IntStream empty() is a method in java.util.stream.IntStream. This method returns an empty sequential IntStream. Syntax : static &lt;T&gt; Stream&lt;T&gt; empty() Where, T is the type of stream elements, and the function returns an empty sequential stream. Example 1 : Creating empty IntStream. // Java code for IntStream empty() import java.util.*; i
1 min read
IntStream distinct() in Java with examples
IntStream distinct() is a method in java.util.stream.IntStream. This method returns a stream consisting of the distinct elements. This is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Syntax : IntStream distinct() Where, IntStream is a sequence of primitive int-valued ele
2 min read
IntStream peek() in Java with examples
IntStream peek() is a method in java.util.stream.IntStream. The function returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. Syntax : IntStream peek(IntConsumer action) Where, IntStream is a sequence of primitive int-valued elemen
3 min read
Stream generate() method in Java with examples
Stream generate(Supplier&lt;T&gt; s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static &lt;T&gt; Stream&lt;T&gt; generate(Supplier&lt;T&gt; s) Where, Stream is an interface and T is the type of s
1 min read
Stream count() method in Java with examples
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
2 min read
IntStream average() in Java with Examples
java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the old problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream average() returns an OptionalDouble describing the arithmetic mean of elements of this strea
2 min read
IntStream max() in Java with examples
java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream max() returns an OptionalInt describing the maximum element of this stream, or an empty optional
2 min read
IntStream min() in Java with Examples
java.util.stream.IntStream in Java 8, deals with primitive ints. It helps to solve the old problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. IntStream min() returns an OptionalInt describing the minimum element of this stream, or an empty opti
2 min read
IntStream count() in Java with examples
IntStream count() returns the count of elements in the stream. IntStream count() is present in java.util.stream.IntStream Syntax : long count() Example 1 : Count the elements in IntStream. // Java code for IntStream count() // to count the number of elements in // given stream import java.util.*; import java.util.stream.IntStream; class GFG { // Dr
2 min read
Stream.of(T... values) in Java with examples
Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static &lt;T&gt; Stream&lt;
2 min read
Stream.of(T t) in Java with examples
Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static &lt;T&gt; Str
2 min read
Stream mapToInt() in Java with examples
Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, the
2 min read
Stream mapToLong() in Java with examples
Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream. Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing,
2 min read
Practice Tags :