File Handling

File handling in C allows you to work with files on your computer's file system. You can use C functions to perform various operations on files, such as:

  • Creating new files
  • Open a file
  • Reading from files
  • Writing to files

File Pointers

In C language, we need pointers to interact with files. We need to declare a file pointer to work with a file.

Opening a File

To open a file for reading and writing, we can use "fopen()" function. It returns a pointer to the targeted file.

In this example:

  • "filename.txt" is the name of the file.
  • "mode" specifies the mode in which we open the file.

Modes

  1. "r" for reading.
  2. "w" for writing.
  3. "a" for appending.

Reading from a File

Reading a file in C can be done using the standard input/output library functions. To read data from a file, we use "fscanf()" or "fgets()" functions.

In this example:

  • "stdio.h" library is used to access file related functions.
  • We declare a pointer of FILE type to interact with the file.
  • Now, we have opened the file using "fopen()" function in read mode.
  • We use a while loop to read the file character by character using fgetc. The loop continues until the end of the file (EOF) is reached.
  • We printed each character in while loop using "putchar".
  • At the end, we close the file using "fclose()" function.

Writing to a File

To write data to a file, you can use functions like fprintf() or fputs().

In this example:

  • "stdio.h" is used to access the file related operations.
  • We declare FILE type pointer to interact with files.
  • We opened the file using "fopen()" in write mode.
  • Now we write data in file using "fputs()" function.
  • Finally, we closed the file using "fclose()" function.

Appending to a File

Appending to a file is similar to writing to a file but we open file in append mode. In append mode, we add data to the end of the file, without overwriting the existing content.

In this example:

  • stdio.h is used to access the file-related functions.
  • We declare a FILE type pointer to interact with files.
  • We open a file using "fopen()" function.
  • We write data to the file using "fputs()" function.
  • Finally, we close the file using "fclose()" function.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min