Sunteți pe pagina 1din 8

C-PROGRAMMING (File Handling)

B.Tech. 1st, 2nd, 3rd & 4th Sem, B.C.A., B.Sc. (Computers & I.T.), PGDCA,
B.Pharmacy
Teacher : Sandeep Sangwan (9417565720, 9417524702, 9463741635)
S.C.F. 204, 2nd Floor (Above Chandigarh Sweets Pvt. Ltd.), Sec-14,
Panchkula

[ C PROGRAMMING ]

Chapter - 08 : File Handling

FILE HANDLING :

Normally, we use the functions such as printf() and scanf() to read and write data. These
are console window related I/O functions, which always use the terminal (keyboard and screen)
as the target place. This works fine as long as the data is small. However, many real life problems
involve large volumes of data and in such situations, the console oriented I/O operations cause
two major problems :
1. It becomes time consuming to handle large volumes of data through terminals like
keyboard and screen.
2. The entire data is lost when either the program is terminated or the computer is turned off.
It is therefore necessary to have a more flexible approach where data can be stored on the
disks and read whenever necessary, without destroying the data. This method employs the
concept of files to store data. A file is a place on the disk where a group of related data is stored.
Like most other languages, C supports a number of functions that have the ability to perform
basic file operations, which include :
Creation of a new file.
Opening an existing file.
Reading data from a file.
Writing data into a file.
Moving to a specific location in a file (seeking)
Closing a file.
Some important file-related functions that are available in the C library are listed below :
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


2

Function

Operation

name
fopen()

Creates a new file for use or opens an existing file for use

fclose()

Closes a file which has been opened for use

fgetc()

Reads a character from a file.

fputc()

Writes a character to a file.

Reads a string from a file.

Writes a string to a file.

Writes a set of data values (record) to a file.

Reads a set of data values from a file.

fwrite()

Reads a set of data values from a file in binary mode.

fseek()

Writes a set of data values from a file in binary mode.

rename()

Sets the position to a desired point in the file.

remove()

To rename a file.

rewind()

To remove a file.

ftell()

Sets the position of the file pointer to the beginning of the file.

Gives the current position in the file (in terms of bytes from the start).

fgets()
fputs()
fprintf()
fscanf()
fread()

OPENING A FILE :

To store or to retrieve the data to and from a file, the file should be opened in the beginning
of the program. To open a file, the function fopen( ) is used. But before opening the file we should
have to declare the file pointer as
FILE *fp;

(fp or any name)

Here, FILE is a structure which is predefined in the header file stdio.h. Therefore, it is
necessary to #include this header file in the program. fp is a structure pointer of type FILE. The
general format for opening a file is :
fp = fopen(filename,mode);
This statement opens the file names filename and assigns an identifier to the FILE type
pointer fp. This pointer which contains all the information about the file is subsequently used as a
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


3

communication link between the system and the program. Once the file has been opened, we no
longer refer to the file by its name, but through the file pointer i.e. fp.
The statement also specifies the purpose of opening this file. The modes does this job.
Following is a list of all the possible modes :

Mode Purpose
r

w
a

r+

w+

a+

Searches file. If the file is opened successful, 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( ) return
NULL.
Operations possible reading from a file.
Searches file. If the file exists, its contents are overwritten. If the file doesnt exist, a new
file is created. Returns NULL, if unable to open file.
Operations possible writing to the file.
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 doesnt exist, a new file is
created. Returns NULL, if unable to open file.
Operations possible adding new contents at the end of file.
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. Returns NULL, if unable to open the file.
Operations possible reading existing contents, writing new contents, modifying
existing contents of the file.
Searches file. If the file exists, its contents are overwritten. If the file doesnt exist, a new
file is created. Returns NULL, if unable to open file.
Operations possible writing new contents, reading them back and modifying
existing contents of the file.
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 doesnt exist, a new file is
created. Returns NULL, if unable to open file.
Operations possible reading existing contents, appending new contents to end of
file. Cannot modify existing contents.

CLOSING A FILE :

When we have finished reading from or writing to a file, we need to close it. This is done
using the function fclose ( ) through the statement,
fclose(fp);
Once we close the file, we can no longer read from or write data to a file unless we reopen
the file. Note that to close the file, we dont use the filename but the file pointer fp.

FILE INPUT AND OUTPUT FUNCTIONS :


CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


4

fputc ( ) :
The fputc( ) function writes characters to a file that was previously opened for writing using
the fopen( ) function. This function has two parameters, a character variable and the file pointer
declared as FILE. The format of fputc( ) function is :
fputc (character variable, file pointer);
For e.g.
fputc(ch, fp);
Where ch is the variable in which character is stored.
Program 1 : WAP to write data character by character into a file.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ( )
{
FILE *fp;
char ch;
clrscr ( );
fp=fopen("data_1.cpp","w");
if (fp==NULL)
{
printf ("\nUnable to create a file");
getch ( );
exit (0);
}
while (ch !=EOF)
{
ch = getchar ( );
fputc (ch, fp);
}
fclose (fp);
}
fgetc( ) :
To read the files contents from memory, there exists a function called fgetc ( ). The format
of this function is:
fgetc(file pointer);
fgetc( ) reads the character from the current pointer position, advances the pointer position so
that it now points to the next character, and returns the character that is read, which we collected
in some character variable. For e.g.
ch = fgetc(fp);
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


5

Program 2 : WAP to read data character by character from a file.


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
FILE *fp;
char ch;
clrscr ();
fp=fopen("data_1.cpp","r");
if(fp==NULL)
{
printf("\nUnable to open file");
getch();
exit(0);
}
while(ch!=EOF)
{
ch=fgetc(fp);
printf("%c",ch);
}
getch();
fclose(fp);
}
Program 3 : WAP to copy the contents of one file to another character by character.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
clrscr( );
FILE *fs,*ft;
char ch;
fs=fopen("data_1.cpp","r");
if(fs==NULL)
{
puts("\nCannot open source file");
getch();
exit(0);
}
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


6

ft=fopen("data1","w");
if(ft==NULL)
{
puts("\nCannot create target file");
getch();
exit(0);
}
while(ch!=EOF)
{
ch=fgetc(fs);
fputc(ch,ft);
}
getch();
fclose(fs);
fclose(ft);
}
Program 4 : WAP to count characters, spaces, tabs and new lines in a file.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main()
{
FILE *fp;
char ch;
int noc=0,nos=0,not=0,nonw=0;
clrscr();
fp=fopen("data_1.cpp","r");
if(fp==NULL)
{
printf("\nUnable to open file");
getch();
exit(0);
}
while(ch!=EOF)
{
ch=fgetc(fp);
noc++;
if(ch==' ')
nos++;
if(ch=='\t')
not++;
if(ch=='\n')
nonw++;
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


7

}
fclose(fp);
printf("\nNumber
printf("\nNumber
printf("\nNumber
printf("\nNumber
getch();
}

of
of
of
of

characters : %d",noc);
spaces
: %d",nos);
tabs
: %d",not);
newlines : %d",nonw);

fputs( ) :
To write the files contents (strings) into the memory, there exists a function called fputs ( ).
The format of this function is :
fputs (string , file pointer);
fputs copies the null-terminated string s to the given output stream. It
does not append a newline character, and the terminating null character is
not copied.
Program 5 : WAP to receives strings from keyboard and writes them to file
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
main()
{
FILE *fp;
char nm[100];
clrscr();
fp=fopen("text_1","w");
if(fp==NULL)
{
printf("\nUnable to create file");
getch();
exit(0);
}
printf("Enter a few lines:\n");
while(strlen(gets(nm))>0)
{
fputs(nm,fp);
fputs("\n",fp);
}
fclose(fp);
}
CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

C-PROGRAMMING (File Handling)


8

fgets( ) :
To read the files contents(strings) from memory, there exists a function called fgets ( ). The
format of this function is :
fgets (string, sizeof(string) 1 , file pointer);
The function fgets( ) takes three arguments. The first is the address where the string is stored,
and the second is the maximum length of the string. This argument prevents fgets() from reading
in too long a string and overflowing the array. The third argument, as usual, is the pointer to the
structure FILE.

CREATIVE INFOTECH, SCF-204(ABOVE CHANDIGARH SWEETS PVT. LTD.), 2ND FLOOR, SEC-14, PKL(9417565720,
9417524702,9463741635)
C, C++, DATA STRUCTURES, MATHEMATICS (B.TECH. 1ST, 2ND, 3RD & 4TH SEM, B.C.A., B.SC. COMPUTERS & I.T., PGDCA,
MCA, B.PHARMACY)

S-ar putea să vă placă și