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

File Handling Note For C Programming

The document provides examples of different file input/output functions in C including: 1) Character I/O using fgetc() and fputc() to read and write individual characters to a file. 2) String I/O using fgets() and fputs() to read and write strings to a file. 3) Record I/O using fprintf() and fscanf() to input/output different data types like structures to files. 4) The differences between text files and binary files and how numbers are stored more efficiently in binary. 5) An example using fread() and fwrite() to store a structure in binary format.

Uploaded by

Hamro Channel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

File Handling Note For C Programming

The document provides examples of different file input/output functions in C including: 1) Character I/O using fgetc() and fputc() to read and write individual characters to a file. 2) String I/O using fgets() and fputs() to read and write strings to a file. 3) Record I/O using fprintf() and fscanf() to input/output different data types like structures to files. 4) The differences between text files and binary files and how numbers are stored more efficiently in binary. 5) An example using fread() and fwrite() to store a structure in binary format.

Uploaded by

Hamro Channel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Character I/O example code[fgetc(), fputc()]:

#include<stdio.h>
int main()
{

FILE *fp;
char ch;
fp = fopen("first.txt","w"); //OPENS in writing mode
printf("Enter characters");
do{
ch = getchar(); //take a character input from user
fputc(ch, fp); //write this character into the file
} while(ch != '\n');
fclose(fp);
fp = fopen("first.txt", "r");
while(1){
ch = fgetc(fp);
if (ch == EOF)
break;
else
putchar(ch);
}
return 0;
}

STRING I/O Example[fgets(), fputs()]:


#include<stdio.h>
int main()
{

FILE *fp;
char str[100];
fp = fopen("second.txt","w");
printf("Enter strings: ");
while(1){
gets(str);
if(strlen(str)>0){
fputs(str, fp);
fputs("\n", fp); //because fputs() doesn't automatically append the newline
}
else
break;
}
fclose(fp);
fp = fopen("second.txt", "r");
while(fgets(str,99,fp)!=NULL){
puts(str);
}
fclose(fp);

return 0;
}
NOTE: fgets (targetstring_array, buffer_size, source_file_pointer);
 targetstring_array is the string array to which we want to store the string being read
 buffer_size prevents from reading in too many string than can be handled
 source_file_pointer is the pointer to the file from which we’re reading

This function returns NULL when we’re done reading.

RECORD I/O or FORMATTED I/O [fprintf(), fscanf()]:


We use these to input/output records or structures i.e. different datatypes. Similar to printf() and scanf().Using
these functions in text mode is time consuming and inefficient because as structures grow, their size increases more
given they’re in text mode, so for such structures and large valued types, we open files in binary mode and use fread()
and fwrite().

#include<stdio.h>
Int main(){
FILE *fp;
char name[100], ch;
int roll;
float marks;
fp = fopen(“third.txt”, “r+”);
if(fp == NULL)
exit(1);
while(fscanf(fp, “%s%d%f”, name, &roll, &marks) != EOF){
printf(“Name: %s\n Roll: %d\n Marks:%f\n”, name, roll, marks);
}

while(1){
printf(“Enter name, roll and marks: “);
scanf(“%s%d%f”, name, &roll, &marks);
fprintf(fp, “%s %d %f” , name, roll, marks);
printf(“if you do not have next data set, enter n”);
scanf(“%c”, ch);
If (ch == ‘n’)
break;

}
rewind(fp); //points the pointer to the start of the file
while(fscanf(fp, “%s%d%f”, name, &roll, &marks)!=EOF){
printf(“Name: %s\n Roll:%d\n Marks:%f\n”,name, roll, marks);
}
fclose(fp);
return 0;
}

EXAMPLE OF STRUCTURE I/O:


#include<stdio.h>
int main()
{

FILE *fp;
int i;
struct student{
char name[30];
int marks;
};
struct student s;
if((fp = fopen("student.txt", "w+")) == NULL)
exit(1);
for (i= 0 ; i<20 ; i++){
printf("Enter name and marks:");
fscanf(stdin,"%s%d",s.name, &s.marks);
fprintf(fp, "%s %d", s.name, s.marks);
}
rewind(fp);
while(fscanf(fp, "%s%d", s.name, &s.marks)!= EOF){
fprintf(stdout, "Name: %s\n Marks: %d\n", s.name, s.marks);
}

fclose(fp);

return 0;
}

All the programs that we wrote so far worked on text files. Some of them would not work correctly on binary
files. A text file contains only textual information like alphabets, digits and special symbols. In actuality the
ASCII codes of these characters are stored in text files. A good example of a text file is any C program, say
PR1.C .
As against this, a binary file is merely a collection of bytes. This collection might be a compiled version of a C
program (say PR1.EXE), or music data stored in a wave file or a picture stored in a graphic file. A very easy way
to find out whether a file is a text file or a binary file is to open that file in Turbo C/C++. If on opening the file
you can make out what is displayed then it is a text file, otherwise it is a binary file.
[Excerpt from Let US C]

Example of a File copy program that works for binary as well as text files.

#include "stdio.h"
void main( )
{
FILE *fs, *ft ;
int ch ;
fs = fopen ( "pr1.exe", "rb" ) ; //rb,wb,etc means binary files mode
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
exit( 1) ;
}
ft = fopen ( "newpr1.exe", "wb" ) ;
if ( ft == NULL )
{
puts ( "Cannot open target file" ) ;
fclose ( fs ) ;
exit( 1) ;
}
while ( 1 )
{
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ;
}
fclose ( fs ) ;
fclose ( ft ) ;
}

DIFFERENCES BETWEEN TEXT FILES AND BINARY FILES:

It differs in three major areas in terms of programming and they are:


 Handling of newlines
 Representation of end of files
 Storage of numbers

1. Text versus Binary Mode: Newlines


We have already seen that, in text mode, a newline character is converted into the carriage return-
linefeed (i.e. when you hit enter it places \r\n) combination before being written to the disk. Likewise,
the carriage return-linefeed combination on the disk is converted back into a newline when the file is
read by a C program. However, if a file is opened in binary mode, as opposed to text mode, these
conversions will not take place.

2. Text versus Binary Mode: End of File


The second difference between text and binary modes is in the way the end-of-file is detected. In text
mode, a special character, whose ASCII value is 26, is inserted after the last character in the file to mark
the end of file. If this character is detected at any point in the file, the read function would return the
EOF signal to the program.
As against this, there is no such special character present in the binary mode files to mark the end of file.
The binary mode files keep track of the end of file from the number of characters present in the
directory entry of the file. There is a moral to be derived from the end of file marker of text mode files. If
a file stores numbers in binary mode, it is important that binary mode only be used for reading the
numbers back, since one of the numbers we store might well be the number 26 (hexadecimal 1A). If this
number is detected while we are reading the file by opening it in text mode, reading would be
terminated prematurely at that point.
Thus the two modes are not compatible. See to it that the file that has been written in text mode is read
back only in text mode. Similarly, the file that has been written in binary mode must be read back only in
binary mode.

3. Text versus Binary Mode: Storage of Numbers


The only function that is available for storing numbers in a disk file is the fprintf( ) function. It is
important to understand how numerical data is stored on the disk by fprintf( ). Text and characters are
stored one character per byte, as we would expect. Are numbers stored as they are in memory, two
bytes for an
integer four bytes for a float, and so on? No. Numbers are stored as strings of characters. Thus, 1234,
even though it occupies two bytes in memory, when transferred to the disk using fprintf( ), would
occupy four bytes, one byte per character. Similarly, the floating-point number 1234.56 would occupy 7
bytes on disk. Thus, numbers with more digits would require more disk space. Hence if large amount of
numerical data is to be stored in a disk file, using text mode may turn out to be inefficient. The solution
is to open the file in binary mode and use those functions ( fread( ) and fwrite( ) which are discussed
later) which store the numbers in binary format. It means each number would occupy same number of
bytes on disk as it occupies in memory.

Example of fread() and fwrite():

#include <stdio.h>
#include<conio.h>
void main( )
{
FILE *fp ;
char another = 'Y' ;
struct emp
{
char name[40] ;
int age ;
float bs ;
};
struct emp e ;
fp = fopen ( "EMP.DAT", "wb" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit(1 ) ;
}
while ( another == 'Y' )
{
printf ( "\nEnter name, age and basic salary: " ) ;
scanf ( "%s %d %f", e.name, &e.age, &e.bs ) ;
fwrite ( &e, sizeof ( e ), 1, fp ) ;
printf ( "Add another record (Y/N) " ) ;
fflush ( stdin ) ;
another = getch( ) ;
}
fclose ( fp ) ;
}
Explanation:

fwrite ( &e, sizeof ( e ), 1, fp ) ;


Here,
1) &e: the first argument is the address of the structure to be written to the disk.
2) sizeof(e): The second argument is the size of the structure in bytes.
3) 1: The third argument is the number of such structures that we want to write at one time. In this case,
we want to write only one structure at a time. Had we had an array of structures, for example, we might
have wanted to write the entire array at once.

Now a program to read the contents of the previous file.

/* Reads records from binary file and displays them on VDU */


#include <stdio.h>
void main( )
{
FILE *fp ;
struct emp
{
char name[40] ;
int age ;
float bs ;
};
struct emp e ;
fp = fopen ( "EMP.DAT", "rb" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit(1 ) ;
}
while ( fread ( &e, sizeof ( e ), 1, fp ) == 1 )
printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;
fclose ( fp ) ;
}

Explanation for fread():


The format is similar to fwrite(). Here once it finishes reading, it returns 0 hence we compare the fread() in while with 1.

You might also like