C – File Handling

File Handling in C includes creating, reading, and writing a file. It also includes deleting a file. To work on files in C programming, we have the fopen() method which is a part of the <stdio.h> header file. To use it, declare a pointer of data type FILE.

Before that, let us first see the syntax of the fopen() method:

Here, file_name is the name of the file you want to create.
The mode is the read mode, write, and append. Only a single character represents the mode:

  • r – read a file
  • w – write to a file
  • a – append to a file

Create and close a File

To create a file in C programming, use the fopen() method and the mode w. Always remember to close an opened file using fclose() method.

Let’s say the name of the file we want to create is myfile.txt at the following location. Use the single backslash in Windows for the path as shown below:

Let us now see an example to create a file in C:

The file myfile.txt gets created at the location. The file is empty since we did not add any text to it:
Create a file in C

Write to a File

To write to a File in C, use the fprintf() method, but before that open the file in w mode like we saw above. Set the pointer in the fprintf() and the text you want to write to the file myfile.txt.

Let us now see the C program to write text to the above file myfile.txt:

The myfile.txt file is now having the following text as shown below:
Write to a File in C

Read a File

To read a file in C Programming, use the fopen() method and the mode r. Always remember to close an opened file using fclose() method.

We will read the above myfile.txt with the following text:

Read a file in c

Let us now see the example to read the above file i.e. myfile.txt that already exists:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


C - Pointers
C Programming Cheat Sheet
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading