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

1020201202:-Data Structures & Algorithms By STP

 FILE HANDLING IN C

 Data files: Many applications require that information be written to or read from an auxiliary memory
device. Such information is stored on the memory device in the form of a data file. Thus, data files
allow us to store information permanently, and to access and alter that information whenever
necessary, without destroyed the data. This method employs the concept of files to store data.

 FILE is a place on the disk where a group of related data is stored.

 What is a stream?

A stream is a sequence of characters. Stream is nothing but the sequence of bytes of data. A sequence of
b ytes flowing into a program is an input-stream; a sequence of bytes flowing out of a program is an
output stream. The major advantage of streams is that input/output programming is device
independent. Programmers do not need to write special input/output functions for each device (k/b,
disk and so on).

 Text versus Binary streams:

C can handle files as Stream oriented data files (Text) and System oriented data files (Binary).

a) Text streams are associated with text-mode files: text-mode files consist of a sequence of lines.
Each line contains zero or more characters and ends with one or more characters that signal end-
of-line. The maximum line length is 255 characters. It is important to remember that a line is not a
C string; there is no terminating NULL character (\0). When you use a text-mode stream,
translation occurs between C’s newline character (\n) and whatever characters the operating
system uses to mark-end-of-line on disk files. On DOS systems, it is a carriage return linefeed
(CR-LF) combination when data is written to a text-mode file, each \n is translated to a CR-LF,
when data is read from a disk file, and each CR-LF is translated as to a \n. On UNIX systems, no
translation is done – newline characters remain unchanged.

b)A binary stream is a collection of bytes. In C, a byte & character are equivalent. The data that is
written into and read from remain unchanged, with no separation into lines and no use of end-of-
line characters.

c) Text file can only be processed (logically) in the forward direction. For this reason a text file is
usually opened for only one kind of operation that is reading, writing or appending, at any given
time. It can only read or write one character at a time. Functions are provided that deal with lines
of text, but these still essentially process one character at a time.

d)Binary file are processed using read and write operations simultaneously.

BMU- BMCCA (BCA) Page 1 of 19


1020201202:-Data Structures & Algorithms By STP

 C File Operation:-
There are five major operations that can be performed on a file are:
1) Creation of a new file
2) Opening an existing file
3) Reading data from a file
4) Writing data in a file
5) Closing a file

 Steps for Processing a file:-

1) Declare a file pointer variable.


2)
3) Open file using fopen() function
4) Process the file using suitable function
5) Close the file using fclose() function

 Input Output Function for file:-

 Defining & Opening File:-

If we want to store data in a file in the secondary storage, we must specify following things:

1) File name
2) Data Structure
3) Purpose / Mode

File name is the string of character that makes up a valid filename for OS. For example test.txt
Data Structure of a file is defined as FILE in the library of standard I/O function definitions. We
have to declare the pointer variable of type FILE. FILE is a defined data type.
We can open file in different modes such as reading mode, writing mode and appending mode
depending on purpose of handling file. The mode can be one of the following:

Mode Description

r Opens an existing text file for reading purpose.

Opens a text file for writing, if it does not exist then a new file is created.
w
Here your program will start writing content from the beginning of the file.

Opens a text file for writing in appending mode, if it does not exist then a new
a file is created. Here your program will start appending content in the existing
file content.

BMU- BMCCA (BCA) Page 2 of 19


1020201202:-Data Structures & Algorithms By STP

r+ Opens a text file for reading and writing both.

Opens a text file for reading and writing both. It first truncate the file to zero
w+
length if it exists otherwise create the file if it does not exist.

Opens a text file for reading and writing both. It creates the file if it does not
a+ exist. The reading will start from the beginning but writing can only be
appended.

If you are going to handle binary files then you will use below mentioned access modes instead of the
above mentioned:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

 Step for Opening the file:-

1) We need pointer variable that points to structure FILE. FILE is a structure declared in stdio.h. The
syntax for declaring the file pointer.

FILE *variable name;

2) After declaring, we open the file. Syntax is:-

fp = fopen(“filename”,”mode”);

Here, fp is a pointer to data type FILE. First argument (filename) is name of the file to be opened
and assigns an identifier to the FILE type pointer fp. This pointer which contains all the information
about the file is subsequently used as communication link between the system and the program.
Second argument (mode) is an access mode like read-r, write-w, append–a. Both filename and
mode are specified as strings. They should be enclosed in double quotation marks.

Example:

FILE *fp1; FILE *fp2;


fp1 = fopen(“stud.dat”,”w”); fp2 = fopen(“mark.dat”,”r”);

We can open and use a number of files at a time.

BMU- BMCCA (BCA) Page 3 of 19


1020201202:-Data Structures & Algorithms By STP

 Closing File:-

Whenever we open a file in read or write mode then we perform appropriate operations on file and
when file is no longer needed then we close the file.
FILE close will flush out all the entries from buffer and all links to the file are broken.
Syntax:-

fclose(file_pointer);

The argument fp is the FILE pointer associated with the stream; fclose() return 0 on success or -1 on
error. When program terminates, all stream are automatically flushed or closed.

Example:-

FILE *fp1, *fp2;


fp1 = fopen(“abc.txt”,”w”);
fp2 = fopen(“xyz.dat”,”r”);
--------
--------
fclose(fp1);
fclose(fp2);

Once a file is closed, its file pointer can be reused for another file. It is a good programming habit to
close a file as soon as the processing is over.

Example for programming of file:-

#include<stdio.h>

void main()
{
FILE *fp;
char ch;
fp = fopen("input.txt","r") // Open file in Read mode
fclose(fp); // Close File after Reading
getch();
}

BMU- BMCCA (BCA) Page 4 of 19


1020201202:-Data Structures & Algorithms By STP

 How Can Read and Write a Single Character for File :-

1) putc( ):-

It writes single characters to a specified stream.

Syntax:-
W

Input
putc(ch,fp); Data
Secondary
fp jOutput Steam storage
device

Where fp is the file pointer returned by fopen() and ch is the character written to the file.

Example:-
putc(‘C’,fp);

2) getc( ):-
It is used to read single characters from a file opened in read mode by fopen().
Syntax:-

char ch;
ch = getc(fp);

Where fp is a file-pointer of type FILE returned by fopen().

R
Output
Ch Devices
Secondary W
storage fp (DATA)
device
fp Input Steam

The file pointer moves by one character position for every operation of getc(). The getc() will return and
end-of-file marker, when the end of the file is reached. Hence the reading will be terminated, when end-
of-file is encountered.

BMU- BMCCA (BCA) Page 5 of 19


1020201202:-Data Structures & Algorithms By STP

Example of programming of file:-

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
scanf(“%c”,&ch);
fp = fopen("input.txt","a") // Open file in Write mode
putc(‘C’,fp);
fclose(fp); // Close File after perform this operation
fp = fopen("input.txt","r") // Open file in Read mode
while((c=getc(fp))!=EOF)//move pointer at end of file
{
printf(“%c”,ch);
}
fclose(fp); // Close File after Reading
getch();
}

 How Can Read interger from and Write into File :-

3) putw( ):-

It writes integer number to a disk file that was previously opened for writing, through the use of the
function fopen().

Syntax:-

putw(n,fp);

Where fp is the file pointer returned by fopen() and n is the integer numbe written to the file.

Example:-

putw(1234,fp);

BMU- BMCCA (BCA) Page 6 of 19


1020201202:-Data Structures & Algorithms By STP

4) getw( ):-

It is used to read integer number from a file opened in read mode by fope().
Syntax:-

int ch;
ch = getw(fp);

Where fp is a file-pointer of type FILE returned by fopen().

Example of programming of file:-

#include<stdio.h>
main( )
{
FILE *f1,*f2,*f3;
int number,I;
int c;
printf("Contents of the data file\n\n");
f1=fopen("database.txt","w");
for(I=0;I<3;I++)
{
scanf("%d",&number);
putw(number,f1);
}
fclose(f1);
f1=fopen("database.txt","r");
while((number=getw(f1))!=EOF)
printf("%d",number);
fclose(f1);
getch();
}

BMU- BMCCA (BCA) Page 7 of 19


1020201202:-Data Structures & Algorithms By STP

 How Can Read and Write a string for File :-

5) fputs( ):-

To write a line of characters to a stream. Also fputs() doesn’t add a newline to the end of the string, if
you want it, you must explicitly include it. It is also included in stdio.h file.

Syntax:-

char fputs(char *str, FILE *fp);

The argument str is a pointer to the null-terminated string to be written and fp is the pointer to the
FILE returned by fopen() when the file was opened. The string pointed to by str is written to the file;
ignoring its terminating \0. The function fputs() returns a non-negative value if successful or EOF an
error.

Example:-

char str[30] = “sneha patel”;


fputs(str,fp);

6) fgets( ):-
To read a line of characters from the file.
Syntax:-

char *fgets(char *str, int n, FILE *fp);

Example:-

char s[20];
fgets(s,5,fp); Ans:- sneha

The argument str is a pointer to buffer in which the input is to be stored, n is the maximum number of
characters to be input, and fp is the pointer to type FILE that was returned by fopen() when the file
was opened.

When called, fgets() reads characters from fp into memory, starting at the location pointed to by str.
Characters are read until a newline is encountered or until n-1 characters have been read, whichever
occurs first. If successful, fgets() returns str. Two types of errors can occur, as indicated by the return
value of NULL.

a) If a read error or EOF is encountered before any characters have been assigned to str, NULL is
returned, and the memory pointed to by str is unchanged.

BMU- BMCCA (BCA) Page 8 of 19


1020201202:-Data Structures & Algorithms By STP

b) If a read error or EOF is encountered after one or more characters have been assigned to str,
NULL is returned and the memory pointed to by str contains garbage.

Example of programming of file:-

#include<stdio.h>
main( )
{
FILE *f1,*f2,*f3;
char *str;
printf("Contents of the data file\n\n");
printf(“\n enter the string:”);
gets(str);
f1=fopen("database.txt","w");
fputs(str,f1);
fclose(f1);
f1=fopen("database.txt","r");
while((fgets(str,sizeof(str),f1))!=NULL)
{
puts(str);
}
fclose(f1);
getch();
}

7) feof( ):-

It can be used to test for an end of file condition.

Syntax:-

feof(file-pointer);

It return non-zero if file-pointer reaches at the end of file otherwise zero value.

BMU- BMCCA (BCA) Page 9 of 19


1020201202:-Data Structures & Algorithms By STP

 How Can Read and Write formatted string for File :-

The I/O functions such as getc(),putc(), getw() and putw() can handle one characater or integer at a
time. But these functions handle a group of mixed data simultaneously. The functions fprintf and
fscanf perform i/o operations similar to printf and scanf function, except that they works on files.

8) fprintf( ):-
It writes formatted string to a disk file that was previously opened for writing, through the use of the
function fopen().
Syntax:-

fprintf(fp,”Control String”,list);

Where fp is a file-pointer associated with a file that has been opened for writing. The control string
contains output specification for the items in the list. The list may include variables, constants and
string.

Example:-
fprintf(fp,”%d %s %f”,123,”sneha”,12.45);

9) fscanf( ):-
It reads the information from the stream specified by stream instead of standard input device.
Syntax:-

fscanf(fp,”Control String”,list);

This statement read the items in the list from the file specified by fp, according to the specifications
contained in the control-string.

BMU- BMCCA (BCA) Page 10 of 19


1020201202:-Data Structures & Algorithms By STP

Example of programming of file:-


WACPT write a structure in a file. The structure should contain no, name of student. Then display data
in proper format.

#include<stdio.h>
void main( )
{
FILE *f1;
int no;
char str[20];
fp = fopen(“data.txt”,”w”);
printf(“\nEnter No:”);
scanf(“%d”,&no);
printf(“\nEnter Name:”);
gets(str);
fprintf(fp,”%d\t%s\n”,no,str);
fclose(fp);
fp=fopen(“data.txt”,”r”);
while(fscanf(fp,”%d %s”,&no,str)!= EOF)
{
printf(“%d\t%s\n”,no,str);
}
fclose(fp);
getch();
}

 Random Access To files:-

1) ftell( ):-

It gives the current position in the file in terms of bytes from the beginning of the file.

Syntax:-

int n;
n = ftell(fp);

BMU- BMCCA (BCA) Page 11 of 19


1020201202:-Data Structures & Algorithms By STP

Where n is a number of type long int and fp is a file-pointer.

2) rewind( ):-

It sets the position of a file-pointer to the beginning of the file.

Syntax:- Example:

rewind(fp); rewind(fp);
n = ftell(fp);

Here n assigns a value zero because the file position has been set to the start of the file by rewind.
Whenever a file is opened for reading or writing, a rewind is done implicitly. Remember that the first
byte in the file is numbered as 0, second as 1 and so on.

3) fseek( ):-

fseek function is used to move the file position to a desired location within the file.

Syntax:-

fseek( fp, offset, position);

Where offset is a member or variable of type long and position is an integer number. The offset
specifies the number positions (in bytes) to be moved from the location specified by position. The
position can take one of the following three values.

0  beginning of file
1  current position
2  end of file
The offset may be positive, meaning moves forwards, or negative meaning moves backwards.

Example:-
fseek(fp,0L,0)  go to the beginning (similar to rewind)
fseek(fp,0L,1)  stay at the current position.
fseek(fp,0L,2)  go to the end of file
fseek(fp,m,0)  move to (m+1) byte(s) in the file.
fseek(fp,m,1)  go forward by m bytes from the current position.
fseek(fp,-m,1)  go backward by m bytes from the current position.
BMU- BMCCA (BCA) Page 12 of 19
1020201202:-Data Structures & Algorithms By STP

fseek(fp,-m,2)  go backward by m bytes from the end of file.


fseek(fp,4,0)  go to 5th bytes in a file.
fseek(fp,4,1)  go forward by 4-bytes from the current position.
fseek(fp,-4,1)  go backward by 4-bytes from the current position.
fseek(fp,-4,2)  go backward by 4-bytes from the end of file.

4) fflush( ):-

The fflush function writes any unwritten data in stream's buffer. If stream is a null pointer, the fflush
function will flush all streams with unwritten data in the buffer.

Syntax:-
int fflush(FILE *stream);
The fflush function returns zero if successful or EOF if an error was encountered.
Example of programming of file:-
Write a program to display file content from desire position.

void main() fgets(str,10,fp);


{ printf("\n%s",str);

FILE *fp; n=ftell(fp);

int n; printf("\n%d",n);
// FP pointer move 4 bytes from end of the file
char str[50];
fseek(fp,-4,SEEK_END);
clrscr();
n=ftell(fp);
fp=fopen("C:\\DATABASE.txt","r");
printf("\nafter SEEK=%d",n);
if(fp==NULL)
fflush(str);
{
fgets(str,10,fp);
printf("not Exists...");
printf("\n%s",str);
} n=ftell(fp);
else printf("\nafter SEEK=%d",n);
{ rewind(fp);
n=ftell(fp); n=ftell(fp);
printf("\ncUrrent position=%d",n); printf("\nafter SEEK=%d",n);
//fp pointer set on location 3
fseek(fp,3,SEEK_CUR); }

n=ftell(fp); fclose(fp);

printf("\nafter move fp pointer from current getch();


position = %d",n); }

BMU- BMCCA (BCA) Page 13 of 19


1020201202:-Data Structures & Algorithms By STP

Example of programming of file:-


Write a program to display file contents in reverse order.

#include<stdio.h> else
main() {
{ fseek(fp,-2L,1);
FILE *fp; printf(“%c\t”,no);
int last; last--;
char no; }
fp = fopen(“hello”,”r”); }
fseek(fp,-1L,2); // set at the last character in the file fclose(fp);
last = ftell(fp); // takes the last value }
printf(“\nFile in reverse order \n”);
while(last != 0L)
{
no = getc(fp);
if(no ==’\n’)
{
fseek(fp,-3,1);
printf(“\n”);
last = last – 2;
}
else
{
fseek(fp,-2L,1);
printf(“%c\t”,no);
last--;
}
}
fclose(fp);
}

BMU- BMCCA (BCA) Page 14 of 19


1020201202:-Data Structures & Algorithms By STP

 Command-line arguments:
All C Programs define a function main() that designates the entry point of program and is invoked
by the environment in which program is executed. In the programs, main() did not take any
arguments. However, main() can be defined with formal parameters so that program may accept
command line arguments, that is, arguments that are specified when the program is executed. That is,
the program must be run from command prompt.

The following syntax of main() allows arguments to be passed from command line:

int main(int argc, char *argv[ ])


{
……
}

In this declaration,

 Main return an integer value (used to determine if the program terminates successfully)
 argc is the number of command line arguments including the command itself, i.e., argc must be at
least 1.
 argv is an array of command line arguments.

Assume that following command is entered in the DOS prompt.

C:\>scopy file1 file2

Upon execution of above command, argc in the main() will take the value three, argv[0] contains the
file name ‘scopy.exe’, argv[1] contains the first string after the name of the program being run, here it
is ‘file1’, argv[2] contains the second string after the name of the program and it is ‘file2’.

When you pass command line arguments to C program, then the main() is written as follows:

BMU- BMCCA (BCA) Page 15 of 19


1020201202:-Data Structures & Algorithms By STP

Example of programming for Command line argument:-

#include<stdio.h> #include<stdio.h>
int main(int argc,char *argv[ ]) int main(int argc,char *argv[ ])
{ {
int i; FILE *fp;
for(i=0;i<argc;i++) int i;
{ char str[30];
printf(“%s”\n,argv[i]); fp = fopen(argv[1],”w”);
} for(i=2;i<argc;i++)
retrun 0; {
} fprintf(fp,”%s\n”,argv[i]);
}
fclose(fp);
fp = fopen(argv[1],”r”);
printf(“No of argument %d and read the data
from %s”,argc,argv[1]);
for(i=2;i<argc;i++)
{
fscanf(fp,”%s\n”,str);
printf(“%s\n”,str);
}
fclose(fp);
getch( );
return 0;
}

BMU- BMCCA (BCA) Page 16 of 19


1020201202:-Data Structures & Algorithms By STP

Question Bank

 Short Question (Marks-2)

1. What is command line argument?


2. What is used of argc and argv?
3. Difference between getc and getchar
4. What is difference between feof and ferror?
Ans:-
 ferror( ):- It checks error in a file during reading process. If error comes ferror returns non zero
value. It continuously returns zero value during reading process.
Syntax:- int error( file pointer)
If the error indicator associated with the stream was set, the function returns a non-zero value else,
it returns a zero value.
 feof( ):- It checks ending of a file. It continuously returns zero value until end of file not come and
return non-zero value when end of file comes.
Example:-

#include <stdio.h>
void main()
{
FILE *fp;
char c;
fp = fopen("file.txt", "w");
c = fgetc(fp);
if(feof(fp)!=0)
{
printf(“\n End of the file…”);
}
if( ferror(fp) )
{
printf("Error in reading from file : file.txt\n");
}
fclose(fp);
getch();
}

BMU- BMCCA (BCA) Page 17 of 19


1020201202:-Data Structures & Algorithms By STP

5. What is signification of EOF (end of file)?


Ans:- The BOF property is automatically set to true when the record pointer is before the first record
in the record set. This condition happens when first record is current and the user chooses Move
Previous. The BOF property is also true if the record set is empty

6. Explain bof (beginning of file).


7. How does an append mode differ from a write mode?
8. What is used of rewind and ftell?
9. Give the difference between scanf( ) and fscanf( ).
10. Give the difference between printf( ) and fprintf( ).
11. List the type of file in C.
12. Dive the difference between text file and binary file.
Ans:- There are three differences between text and binary mode files :
Purpose Text File Binary File
Handling of In text mode, a newline character is if a file is opened in binary mode,
newlines: converted into the carriage return- as opposed to text mode, these
linefeed combination before being conversions will not take place
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.

Representatio In text mode, a special character, There is no such special character


n of end of whose ASCII value is 26, is present in the binary mode files to
file: inserted after the last character in mark the end of file. The binary
the file to mark the end of file. If mode files keep track of the end of
this character is detected at any file from the number of character
point in the file, the read function present in the directory entry of the
would return the EOF signal to the file
program

Storage of In text file the text and characters if large amount of data is to be
numbers: are stored one character per byte. stored in a disk file.The file is to
But numbers are stored as strings open in binary mode and use those
of characters. It occupies 4 bytes in functions (fread() and fwrite()) )
memory, when transferred to the which store the numbers in binary
disk using fprintf(), would occupy format. It means each number
5 bytes, one byte per character. would occupy same number of
Here if large amount of data is to bytes on disks as it occupies in
be stored in a disk file, using text memory.
mode may turn out to be
insufficient

BMU- BMCCA (BCA) Page 18 of 19


1020201202:-Data Structures & Algorithms By STP

 Long Question: (marks-5-7)

1. Explain the command line argument.


2. Notes on Random access file in C.(ftell, rewind,fseek & fflush)
3. Explain the general format of fseek function?
4. How can you define, open and close the file?
5. Why file handling is required? How to define file? How to open and close file? Explain with
proper example.
6. Explain fprintf and fscanf function with example. OR formatted string function
7. Explain a) fgets() and fputs() b) getc() and putc() c) getw and putw()
8. What is file? Also explain reding and writing records operations to a file.
9. Difference between Sequential access and Random access.

BMU- BMCCA (BCA) Page 19 of 19

You might also like