Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

File Handling in C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

File Handling 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.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o 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 for opening a file is:
FILE *fopen( const char * filename, const char * mode );

Mode Description
r opens a text file in read mode
0w 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 accepts two parameters:

o 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".

o 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.

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 performed 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 file 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)
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


char dataToBeRead[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;
}
OUTPUT:
The file is now opened.

Data successfully read from file GfgTest.c

The file is now closed.


Program to Open a File, Write in it, And Close the File
#include<stdio.h>

#include<conio.h>

int main( )

{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
char dataToBeWritten[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") ;
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;
}

OUTPUT:
The file is now opened.

Data successfully written in file GfgTest.c

The file is now closed.

You might also like