UNIT- 6
File Management in C
In programming, we may require some specific input data to be generated several numbers of times. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program. The following operations can be performed on a file.
- Creation of the new file
- Opening an existing file
- Reading from the file
- Writing to the file
- Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A list of file functions are given below:
No. | Function | Description |
1 | Fopen() | Opens new or existing file |
2 | Fprintf() | Write data into the file |
3 | Fscanf() | Reads data from the file |
4 | Fputc() | Writes a character into the file |
5 | Fgetc() | Reads a character from file |
6 | Fclose() | Closes the file |
7 | Fseek() | Sets the file pointer to given position |
8 | Fputw() | Writes an integer to file |
9 | Fgetw() | Reads an integer from file |
10 | Ftell() | Returns current position |
11 | Rewind() | Sets the file pointer to the beginning of the file |
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.
- FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
- The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
- The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.
Mode | Description |
R | Opens a text file in read mode |
W | Opens a text file in write mode |
A | Opens a text file in append mode |
r+ | Opens a text file in read and write mode |
w+ | Opens a text file in read and write mode |
a+ | Opens a text file in read and write mode |
Rb | Opens a binary file in read mode |
Wb | Opens a binary file in write mode |
Ab | Opens a binary file in append mode |
Rb+ | Opens a binary file in read and write mode |
Wb+ | Opens a binary file in read and write mode |
Ab+ | Opens a binary file in read and write mode |
The fopen function works in the following way.
- Firstly, It searches the file to be opened.
- Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency for the read operations.
- It sets up a character pointer which points to the first character of the file.
Consider the following example which opens a file in write mode.
- #include<stdio.h>
- Void main( )
- {
- FILE *fp ;
- Char ch ;
- Fp = fopen("file_handle.c","r") ;
- While ( 1 )
- {
- Ch = fgetc ( fp ) ;
- If ( ch == EOF )
- Break ;
- Printf("%c",ch) ;
- }
- Fclose (fp ) ;
- }
Output
The content of the file will be printed.
#include;
Void main( )
{
FILE *fp; // file pointer
Charch;
Fp = fopen("file_handle.c","r");
While ( 1 )
{
Ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.
If ( ch == EOF )
Break;
Printf("%c",ch);
}
Fclose (fp );
}
Closing a file
Most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. Different operations that can be performed on a file are:
- Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
- Opening an existing file (fopen)
- Reading from file (fscanf or fgets)
- Writing to a file (fprintf or fputs)
- Moving to a specific location in a file (fseek, rewind)
- Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.
Functions in File Operations:
File opening modes in C:
“r” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
“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 file.
“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 file.
“r+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which 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 file.
“a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
As given above, if you want to perform operations on a binary file, then you have to append ‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use “a+b”. For performing the operations on the file, a special pointer called File pointer is used which is declared as
FILE *filePointer;
So, the file can be opened as
FilePointer = fopen(“fileName.txt”, “w”)
The second parameter can be changed to contain all the attributes listed in the above table.
Reading from a file –
The file read operations can be performed using functions fscanf or fgets. Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. So, it depends on you if you want to read the file line by line or character by character.
And the code snippet for reading a file is as:
FILE * filePointer;
FilePointer = fopen(“fileName.txt”, “r”);
Fscanf(filePointer, "%s %s %s %d", str1, str2, str3, &year);
Writing a file –:
The file write operations can be perfomed by the functions fprintf and fputs with similarities to read operations. The snippet for writing to a file is as :
FILE *filePointer ;
FilePointer = fopen(“fileName.txt”, “w”);
Fprintf(filePointer, "%s %s %s %d", "We", "are", "in", 2012);
Closing a file –:
After every successful fie operations, you must always close a file. For closing a file, you have to use fclose function. The snippet for closing a file is given as :
FILE *filePointer ;
FilePointer= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
Fclose(filePointer)
Example 1: Program to Open a File, Write in it, And Close the File
Filter_none
Brightness_4
// C program to Open a File,
// Write in it, And Close the File
# include <stdio.h>
# include <string.h>
Int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
ChardataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";
// Open the existing file GfgTest.c using fopen()
// in write mode using "w" attribute
FilePointer = fopen("GfgTest.c", "w") ;
// Check if this filePointer is null
// which maybe if the file does not exist
If ( filePointer == NULL )
{
Printf( "GfgTest.c file failed to open." ) ;
}
Else
{
Printf("The file is now opened.\n") ;
// Write the dataToBeWritten into the file
If ( strlen ( dataToBeWritten ) > 0 )
{
// writing in the file using fputs()
Fputs(dataToBeWritten, filePointer) ;
Fputs("\n", filePointer) ;
}
// Closing the file using fclose()
Fclose(filePointer) ;
Printf("Data successfully written in file GfgTest.c\n");
Printf("The file is now closed.") ;
}
Return 0;
}
Example 2: Program to Open a File, Read from it, And Close the File
Filter_none
Brightness_4
// C program to Open a File,
// Read from it, And Close the File
# include <stdio.h>
# include <string.h>
Int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Declare the variable for the data to be read from file
ChardataToBeRead[50];
// Open the existing file GfgTest.c using fopen()
// in read mode using "r" attribute
FilePointer = fopen("GfgTest.c", "r") ;
// Check if this filePointer is null
// which maybe if the file does not exist
If ( filePointer == NULL )
{
Printf( "GfgTest.c file failed to open." ) ;
}
Else
{
Printf("The file is now opened.\n") ;
// Read the dataToBeRead from the file
// using fgets() method
While(fgets ( dataToBeRead, 50, filePointer ) != NULL )
{
// Print the dataToBeRead
Printf( "%s" , dataToBeRead ) ;
}
// Closing the file using fclose()
Fclose(filePointer) ;
Printf("Data successfully read from file GfgTest.c\n");
Printf("The file is now closed.") ;
}
Return 0;
}
We need files to store the output of a program when the program terminates. Using files, we can access related information using various commands in different languages.
Here is a list of some operations that can be carried out on a file −
- Creating a new file
- Opening an existing file
- Reading file contents
- Searching data on a file
- Writing into a new file
- Updating contents to an existing file
- Deleting a file
- Closing a file
Writing into a File
To write contents into a file, we will first need to open the required file. If the specified file does not exist, then a new file will be created.
Let’s see how to write contents into a file using C++.
Example
#include <iostream>
#include <fstream>
Using namespace std;
Int main () {
Ofstreammyfile;
Myfile.open ("Tempfile.txt", ios::out);
Myfile<< "Writing Contents to file.\n";
Cout<< "Data inserted into file";
Myfile.close();
Return 0;
}
Note−
- Fstream is the stream class used to control file read/write operations.
- Ofstream is the stream class used to write contents into file.
Let’s see how to write contents into a file using Erlang, which is a functional programming language.
-module(helloworld).
-export([start/0]).
Start() ->
{ok, File1} = file:open("Tempfile.txt", [write]),
File:write(File1,"Writting contents to file"),
Io:fwrite("Data inserted into file\n").
Note−
- To open a file we have to use, open(filename,mode).
- Syntax to write contents to file: write(filemode,file_content).
Output− When we run this code “Writing contents to file” will be written into the file Tempfile.txt. If the file has any existing content, then it will be overwritten.
Reading from a File
To read from a file, first we have to open the specified file in reading mode. If the file doesn’t exist, then its respective method returns NULL.
The following program shows how to read the contents of a file in C++−
#include <iostream>
#include <fstream>
#include <string>
Using namespace std;
Int main () {
Stringreadfile;
Ifstreammyfile ("Tempfile.txt",ios::in);
If (myfile.is_open()) {
While ( getline (myfile,readfile) ) {
Cout<<readfile<< '\n';
}
Myfile.close();
} else
Cout<< "file doesn't exist";
Return 0;
}
It will produce the following output −
Writing contents to file
Note−In this program, we opened a text file in read mode using “ios::in” and then print its contents on the screen. We have used while loop to read the file contents line by line by using “getline” method.
The following program shows how to perform the same operation using Erlang. Here, we will use the read_file(filename) method to read all the contents from the specified file.
-module(helloworld).
-export([start/0]).
Start() ->
Rdfile = file:read_file("Tempfile.txt"),
Io:fwrite("~p~n",[rdfile]).
It will produce the following output −
Ok, Writing contents to file
Delete an Existing File
We can delete an existing file using file operations. The following program shows how to delete an existing file using C++−
#include <stdio.h>
Int main () {
If(remove( "Tempfile.txt" ) != 0 )
Perror( "File doesn’t exist, can’t delete" );
Else
Puts( "file deleted successfully " );
Return 0;
}
It will produce the following output −
File deleted successfully
The following program shows how you can perform the same operation in Erlang. Here, we will use the method delete(filename) to delete an existing file.
-module(helloworld).
-export([start/0]).
Start() ->
File:delete("Tempfile.txt").
Output− If the file “Tempfile.txt” exists, then it will be deleted.
Determining the Size of a File
The following program shows how you can determine the size of a file using C++. Here, the function fseek sets the position indicator associated with the stream to a new position, whereas ftell returns the current position in the stream.
#include <stdio.h>
Int main () {
FILE * checkfile;
Long size;
Checkfile = fopen ("Tempfile.txt","rb");
If (checkfile == NULL)
Perror ("file can’t open");
Else {
Fseek (checkfile, 0, SEEK_END); // non-portable
Size = ftell (checkfile);
Fclose (checkfile);
Printf ("Size of Tempfile.txt: %ld bytes.\n",size);
}
Return 0;
}
Output− If the file “Tempfile.txt” exists, then it will show its size in bytes.
The following program shows how you can perform the same operation in Erlang. Here, we will use the method file_size(filename) to determine the size of the file.
-module(helloworld).
-export([start/0]).
Start() ->
Io:fwrite("~w~n",[filelib:file_size("Tempfile.txt")]).
Output− If the file “Tempfile.txt” exists, then it will show its size in bytes. Else, it will display “0”.
Error handling helps you during the processing of input-output statements by catching severe errors that might not otherwise be noticed. For input-output operations, there are several important error-handling phrases and clauses. These are as follows:
- AT END phrase
- INVALID KEY phrase
- NO DATA phrase
- USE AFTER EXCEPTION/ERROR declarative procedure
- FILE STATUS clause.
During input-output operations, errors are detected by the system, which sends messages; the messages are then monitored by ILE COBOL. As well, ILE COBOL will detect some errors during an input-output operation without system support. Regardless of how an error is detected during an input-output operation, the result will always be an internal file status of other than zero, a runtime message, or both.
An important characteristic of error handling is the issuing of a runtime message when an error occurs during the processing of an input-output statement if there is no AT END/INVALID KEY phrase in the input-output statement, USE AFTER EXCEPTION/ERROR procedure, or FILE STATUS clause in the SELECT statement for the file.
One thing to remember about input-output errors is that you choose whether or not your program will continue running after a less-than-severe input-output error occurs. ILE COBOL does not perform corrective action. If you choose to have your program continue (by incorporating error-handling code into your design), you must also code the appropriate error-recovery procedure.
Besides the error-handling phrases and clauses that specifically relate to input-output statements, user defined ILE condition handlers and ILE COBOL error handling APIs can also be used to handle I/O errors.
For each I/O statement, ILE COBOL registers a condition handler to catch the various I/O related conditions. These condition handlers are registered at priority level 185 which allows user defined condition handlers to receive control first.
As mentioned above, an ILE COBOL runtime message is issued when an error occurs and no appropriate AT END, INVALID KEY, USE procedure, or FILE STATUS clause exists for a file. The message, LNR7057, is an escape message. This message can be handled by a user-defined condition handler. If no condition handler can handle this message, message LNR7057 will be resent as a function check.
ILE COBOL has a function check condition handler that will eventually issue inquiry message LNR7207 unless an ILE COBOL error handling API has been defined.
Text Books:
1. Fundamental of Information Technology by A.Leon&M.Leon.
2. Let Us C by YashwantKanetkar.
3. Computer Fundamentals and Programming in C by A. K. Sharma, Universities Press.
Reference Books:
1. Programming in C by Schaum Series.
2. Computer Networks (4th Edition) by Andrew S. Tanenbaum
3. Digital Principles and Application by Donald Peach, Albert Paul Malvino
4. Operating System Concepts, (6th Edition) by Abraham Silberschatz, Peter Baer Galvin, Greg Gagne