0% found this document useful (0 votes)
60 views

Unit 5 Basics of File Handling

This document discusses files and file handling in C programming. It provides three key points: 1. Files are needed to preserve data, provide easy access, and allow data to be transported between computers. 2. There are two main types of files in C - text files (ASCII files) which contain human-readable text, and binary files which contain data in binary format. 3. Basic file operations in C include creating/opening a file, reading from a file, writing to a file, and closing a file. These are performed using functions like fopen(), fread(), fwrite(), and fclose().

Uploaded by

Parshva Dani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Unit 5 Basics of File Handling

This document discusses files and file handling in C programming. It provides three key points: 1. Files are needed to preserve data, provide easy access, and allow data to be transported between computers. 2. There are two main types of files in C - text files (ASCII files) which contain human-readable text, and binary files which contain data in binary format. 3. Basic file operations in C include creating/opening a file, reading from a file, writing to a file, and closing a file. These are performed using functions like fopen(), fread(), fwrite(), and fclose().

Uploaded by

Parshva Dani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Why Files are needed :

• To preserve data
• Easy access
• Transportable on any computer

C programming language supports two types of files and they are as follows...

• Text Files (or) ASCII Files


• Binary Files

Text file : The file that contains ASCII codes of data like digits, alphabets and symbols is called text
file (or) ASCII file.
 Normal text file that can be accessed using Notepad
 Displays normal text content that can be edited or deleted.
 Takes minimum effort to maintain, easily readable, less security and takes bigger storage
space.
Binary File : The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files.
 .bin files in computer
 Stores data in binary form, holds large amount of data, provides better security.

File Operations in C
The following are the operations performed on files in c programming langauge...

• Creating (or) Opening a file


• Reading data from a file
• Writing data into a file
• Closing a file

All the above operations are performed using file handling functions available in C. We discuss file
handling functions in the next topic.
Different operations that can be performed on a file are:

1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w+”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgets)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.
Functions in File Operations:
Opening or creating file
For opening a file, fopen function is used with the required access modes. Some of the commonly
used file access modes are mentioned below.
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.
• “rb” – Open for reading in binary mode. If the file does not exist, 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.
• “wb” – Open for writing in binary mode. If the file exists, its contents are overwritten. If the
file does not exist, it will be created.
• “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.
• “ab” – Open for append in binary mode. Data is added to the end of the file. If the file does not
exist, it will be created.
• “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.
• “rb+” – Open for both reading and writing in binary mode. If the file does not exist, 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.
• “wb+” – Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
• “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.
• “ab+” – Open for both reading and appending in binary mode. If the file does not exist, it will
be created.
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 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)
FILE STREAMS:
 Abstraction between the programmer and the device.
 Sequence of bytes of data.
 File I/O takes place through two streams : Input stream & Output stream.
So far, we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively.

 To perform file processing in C++, header files <iostream> and <fstream> must be included in
your C++ source file.

Sr.No Data Type & Description

1
ofstream
This data type represents the output file stream and is used to create files and to write information to files.

2
ifstream
This data type represents the input file stream and is used to read information from files.

3
Fstream
This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means
it can create files, write information to files, and read information from files.

File Pointer :

Points to the memory location that contains information about the file.
● Name of the file
● Current position of the file
● Mode of the file
● Track errors in the file
Syntax:

FILE * filePointer;

Example 1: Program to Open a File, Write in it, And Close the File

// 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

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") ;

// 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

// 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

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;

Example 3: Program to write to a Binary file using fwrite()


#include <stdio.h>

#include <stdlib.h>

struct threeNum

int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

for(n = 1; n < 5; ++n) //Program Code Submitted by Susobhan Akhuli

num.n1 = n;

num.n2 = 5*n;

num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);

fclose(fptr);

return 0;

Example 4: Program to Read from a binary file using fread()


#include <stdio.h>

#include <stdlib.h>

struct threeNum

int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

for(n = 1; n < 5; ++n) //Program Code Submitted by Susobhan Akhuli

fread(&num, sizeof(struct threeNum), 1, fptr);

printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);

}
fclose(fptr);

return 0;

You might also like