Till now, In every Tutorial we used to display the output of every program on the console/terminal. But in the Programming Industry, we may have to build large programs, where the output generated may be very large and it cannot be displayed on the screen, and due to the volatile nature of memory, the data(generated by the program for an instance) lost to it may never be recovered, and in such cases we need to store the output in a file, that may be present on the local file system or on the cloud/online.
File is a collection of bytes, regardless of the type, either binary or text stored on the System. C Language provides us with several powerful functions and methods to perform several operations on files like search, create, read, write, delete etc. Some terms might consider confusing to you, but don't worry we would be learning about each of them in detail.
Why we need Files
- Files are needed to store the enormous amount of Data generated by a program, because it would be a very bulky task to obtain the Data again and again, by running the program, as when the program is terminated, the data is lost, and since it is volatile, it cannot be recovered.
- For the ease in transportation of Data from one system to another.
- Storing data on files helps in reducing the time, we waste in inputting the data.
Types of Files
- Text(ASCII) Files : These are the simple text files having extension .txt ,which can be created by any text-editor like notepad etc. Its contents are displayed in form of simple plain text. These files have the least security, but editing them or maintaining them is a very easy task.
- Binary Files : These are the files having extension .bin ,they store data in the form 0's and 1's, i.e in Binary Format, They are more secure than Text files as the data stored on them is not easily readable.
Basics of File Operations
- Creating a new file
- Opening an existing file
- Reading from that file
- Writing to that file
- Closing the file
Introduction to File Modes
Working with Files
Opening/Creating a file
Important Points about some File Modes:
- The 'r' mode as we know opens the file for reading, but if it is unable to open the file, then it returns NULL.
- 'w' mode firstly searches the file that is to be open, and if it is found then it overwrites its contents. But if the file is not found, then it automatically creates a new file. And it also returns NULL if it is unable to open the file.
- Most functions return NULL, in case they cannot open the file due to some reason.
- 'a' mode when used it loads the file in the memory for adding data to it, unlike 'w' it does not overwrite the previous contents of the file.