Logo
Unit 11 – File Handling in C

File Handling in C

Duration: 5 minutes

Hey there coders!

We’ve covered some of the basics of understanding C. However, understanding file handling is pivotal for working with external data storage. This aspect of C programming allows you to interact with files, read data from them, and write data into them.

Basics of File Handling in C

In C, file handling involves using the ‘FILE’ structure and a set of functions provided by the Standard Input/Output Library (‘stdio.h’). The primary operations include opening, reading, writing, and closing files.

Opening a File

To open a file, we use the ‘fopen’ function, specifying the file name and the mode (read, write, append, etc.).

FILE *filePointer;
filePointer = fopen("example.txt", "w");

In this example, we open a file named example.txt in write mode (“w”).

Reading and Writing to a File

To read from a file, we use ‘fscanf’, and to write to a file, we use ‘fprintf’.

// Writing to a file
fprintf(filePointer, "Hello, File Handling in C!");
// Reading from a file
char buffer[100];
fscanf(filePointer, "%s", buffer);

Closing a File

It’s crucial to close a file after performing operations on it using the ‘fclose’ function.

fclose(filePointer);

Exercise

Now, let’s apply our understanding by creating and manipulating a text file:

  • File Creation: Use fopen to create a text file named example.txt in write mode.
  • Writing to File: Use fprintf to write a sentence or phrase into the text file.
  • Reading from File: Use fscanf to read the content from the file and store it in a buffer.
  • Output: Print the content of the buffer to the console.

This exercise will provide you with hands-on experience creating and manipulating a text file in C.

Conclusion

Fantastic! You’ve now delved into the basics of file handling in C. This skill is indispensable for interacting with external data and creating more dynamic and data-driven programs. As you continue your C programming journey, you’ll encounter more advanced file-handling techniques. Keep coding and exploring the diverse possibilities of working with files in C!

Next Tutorial: Preprocessors and Macros

5 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!