Vous êtes sur la page 1sur 18

File handling functions

In this article, we will cover the following


functions that are popularly used in file
handling :
fopen()

FILE *fopen(const char *path, const char


*mode);

The fopen() function is used to open a file


and associates an I/O stream with it. This
function takes two arguments. The first
argument is a pointer to a string
containing name of the file to be opened
while the second argument is the mode in

which the file is to be opened. The mode


can be :
r : Open text file for reading. The
stream is positioned at the beginning
of the file.
r+ : Open for reading and writing.
The stream is positioned at the
beginning of the file.
w : Truncate file to zero length or
create text file for writing. The stream
is positioned at the beginning of the
file.
w+ : Open for reading and writing.
The file is created if it does not exist,
otherwise it is truncated. The stream is
positioned at the beginning of the file.

a : Open for appending (writing at


end of file). The file is created if it does
not exist. The stream is positioned at
the end of the file.
a+ : Open for reading and appending
(writing at end of file). The file is
created if it does not exist. The initial
file position for reading is at the
beginning of the file, but output is
always appended to the end of the file.
The fopen() function returns a FILE
stream pointer on success while it returns
NULL in case of a failure.
fread() and fwrite()

size_t fread(void *ptr, size_t size, size_t


nmemb, FILE *stream);

size_t fwrite(const void *ptr, size_t size, size_t


nmemb, FILE *stream);

The functions fread/fwrite are used for


reading/writing data from/to the file
opened by fopen function. These functions
accept three arguments. The first
argument is a pointer to buffer used for
reading/writing the data. The data
read/written is in the form of nmemb
elements each size bytes long.
In case of success, fread/fwrite return the
number of bytes actually read/written

from/to the stream opened by fopen


function. In case of failure, a lesser
number of byes (then requested to
read/write) is returned.
fseek()

int fseek(FILE *stream, long offset, int


whence);

The fseek() function is used to set the file


position indicator for the stream to a new
position. This function accepts three
arguments. The first argument is the FILE
stream pointer returned by the fopen()
function. The second argument offset
tells the amount of bytes to seek. The third
argument whence tells from where the

seek of offset number of bytes is to be


done. The available values for whence are
SEEK_SET, SEEK_CUR, or SEEK_END.
These three values (in order) depict the
start of the file, the current position and
the end of the file.
Upon success, this function returns 0,
otherwise it returns -1.
fclose()

int fclose(FILE *fp);

The fclose() function first flushes the


stream opened by fopen() and then closes
the underlying descriptor. Upon
successful completion this function

returns 0 else end of file (eof) is returned.


In case of failure, if the stream is accessed
further then the behavior remains
undefined.
The code

The simplest way that C programming information is stored


in a file issequentially, one byte after the other. The file
contains one long stream of data.
File access in C is simply another form of I/O. Rather than
go to the display, the input or output goes into a file. A file is
opened by using the fopen() function:
handle=fopen(filename,mode);
The fopen() function requires two arguments, both strings.
The first is a filename; the second is a mode. The fopen()
function returns a file handle, which is a pointer used to
reference the file. That pointer is a FILE type of variable.
Mod

File Open

Create

for

File?

"a"

Appending

Yes

Notes

It adds to the end of

an existing file; a file


is created if it doesnt
exist.
" a+"

Appending

Yes

and reading
"r"

Reading

Information is added
to the end of the file.

No

If the file doesnt exist,


fopen() returns an
error.

"r+"

Reading

No

and writing
"w"

Writing

If the file doesnt exist,


an error is returned.

Yes

The existing file is


overwritten if the
same name is used.

"w+"

Writing and
reading

Yes

The existing file is


overwritten.

The mode is a string. Even when only one character is


specified, it must be enclosed in double quotes.
After the file is open, you use the handle variable to
reference the file as you read and write. The file I/O
functions are similar to their standard I/O counterparts, but

with an f prefix. To write to a file, you can use the fprintf(),


fputs(), fputchar(), and similar functions. Reading from a file
uses the fscanf(), fgets(), and similar functions.
You close the file by using the fclose() function with the file
handle as its argument.
How to write text to a file

Write That File demonstrates the basic process of creating


a new file, writing text to that file, and then closing file
access.
WRITE THAT FILE
#include<stdio.h>
#include<stdlib.h>
intmain()
{
FILE*fh;
fh=fopen("hello.txt","w");
if(fh==NULL)
{
puts("Can'topenthatfile!");
exit(1);
}
fprintf(fh,"LookwhatImade!\n");
fclose(fh);
return(0);

}
Line 6 creates the file handle, fh. Its a pointer. The pointer
stores the result of the fopen() function from Line 8. The file
hello.txt is created using the "w" (write) mode. If the file
exists, its overwritten.
The if statement checks to confirm that the file was properly
opened. If it wasnt, the value of fh is NULL, and
appropriate action is taken.
The fprintf() function writes text to the file at Line 14. The
format is the same as for printf(), although the file handle
must be included as an argument.
Finally, Line 15 closes the file by using the fclose() function.
This statement is a required step for any file access
programming.
Exercise 1: Copy the source code from Write That File into
your editor. Build and run the program.
The programs output goes to a file, so you dont see
anything displayed when its run. Use your computers file
browser to locate the file and open it. Or you can write a
program that reads the text from that same file.

How to read text from a file

The standard C text-reading functions are used to read text


from a file just as they read text from the keyboard. For
reading text one character at a time, use the fgetc()
function.
READ THAT FILE
#include<stdio.h>
#include<stdlib.h>
intmain()
{
FILE*fh;
intch;
fh=fopen("hello.txt","r");
if(fh==NULL)
{
puts("Can'topenthatfile!");
exit(1);
}
while((ch=fgetc(fh))!=EOF)
putchar(ch);
fclose(fh);
return(0);
}

Line 9 in Read That File opens the file hello.txt for reading
only. The file must exist or else an error occurs.
The while loop at Line 15 displays the files contents one
character at a time. The fgetc() function reads one
character from the file identified by handle fh. That
character is stored in variable ch. The result is compared
with the End of File constant. When theres a match, the file
has been completely read and the while loop stops.
Otherwise, the character thats read is displayed on Line
16.
Exercise 2: Create a new program by using the source
code shown in Read That File. Build and run.
The program displays the contents of the file created by
Exercise 1; otherwise, you see the error message.
Exercise 3: Modify your source code from Exercise 1 to
write a second string to the file. Add the following statement
after Line 14:
fputs("MyCprogramwrotethisfile.\n",fh);
Unlike using the puts() statement, you need to specify a
newline character for fputs() output. Further, the file handle
argument appears after the string, which is unusual for a C
language file function.

The two file-writing functions fprintf() and fputs() write text to


the file sequentially, one character after the other. The
process works just like writing text to the screen, but
instead those characters are saved in a file in permanent
storage.
The fgets() function reads an entire string of text from a file.
To make it work, you need an input buffer, the number of
characters to read, and the file handle.
GULPING STRINGS OF TEXT
#include<stdio.h>
#include<stdlib.h>
intmain()
{
FILE*fh;
charbuffer[64];
fh=fopen("hello.txt","r");
if(fh==NULL)
{
puts("Can'topenthatfile!");
exit(1);
}
while(fgets(buffer,64,fh))
printf("%s",buffer);
fclose(fh);
return(0);

}
The fgets() function appears at Line 15 as the while loops
condition. Thats because fgets() returns a pointer to the
string thats read, and when no string is read, it returns a
NULL. That value stops the loop. Otherwise, the printf()
function at Line 16 displays the input.
The buffer size and the size of characters read in Gulping
Strings of Text are identical. Thats because the \0 at the
end of the string is read from the file and isnt interpreted as
an end-of-file marker.
Exercise 4: Type the source code from Gulping Strings of
Text into your editor. Build and run.
This lesson is about using random access files in C and the
following lesson will look at working with text files. Apart
from the simplest of applications, most programs have to
read or write files. Maybe it's just for reading a config file, or
a text parser or something more sophisticated. The basic
file operations are

fopen - open a file- specify how its opened (read/write)


and type (binary/text)

fclose - close an opened file

fread - read from a file

fwrite - write to a file

fseek/fsetpos - move a file pointer to somewhere in a

file.

ftell/fgetpos - tell you where the file pointer is located.


There are two fundamental types of file: text and binary. Of
these two, binary are generally the simpler to deal with. As
doing random access on a text file isn't something you need
to do too often, we'll stick with binary files for the rest of this
lesson. The first four operations listed above are for both
text and random access files. The last two just for random
access.
Random access means we can move to any part of a file
and read or write data from it without having to read through
the entire file. Back thirty years ago, much data was stored
on large reels of computer tape. The only way to get to a
point on the tape was by reading all the way through the
tape. Then disks came along and now we can read any part
of a file directly.
On the next page : Programming with Binary Files
A binary file is a file of any length that holds bytes with
values in the range 0 to 0xff. (0 to 255). These bytes have
no other meaning unlike in a text file where a value of 13
means carriage return, 10 means line feed, 26 means end
of file and software reading text files has to deal with these.

In modern terms we call binary files a stream of bytes and


more modern languages tend to work with streams rather
than files.
The important part is the data stream rather than where it
came from! In C you can think about the data either in terms
of files or streams. Or if it helps, think of a file/stream as a
very long array! With random access you can read or write
to any part of this array. With sequential you have to loop
through it from the start like a big tape.
Download Example 1.
This shows a simple binary file being opened for writing,
with a text string (char *) being written into it. Normally you'd
use a text file for that but I wanted to show that you can
write text to a binary file.
// ex1.c #include <stdio.h> #include
<string.h>

int main(int argc, char *

argv[]) {

const char *

filename="test.txt";

const char *

mytext="Once upon a time there were three


bears.";

int byteswritten=0;

fopen(filename, "wb") ;

FILE * ft=

if (ft) {

fwrite(mytext,sizeof(char),strlen(mytext
), ft) ;

fclose( ft ) ;

printf("len of mytext = %i
",strlen(mytext)) ;

return 0; }

Random Access to file in C


Random access means we can move to any part of a file and read or write data from it
without having to read through the entire file. we can access the data stored in the file in
two ways.

1.

Sequentially

2.

Randomly

if we want to access the forty fourth record then first forty three record read sequentially
to reach forty four record. In random access data can be accessed and processed
directly .There is no need to read each record sequentially. If we want to access a
particular record random access takes less time than the sequential access.
C supports these function for random access file.

1.

fseek( ) Function

2.

ftell ( ) Function

How to use fseek() function in C


This function is used for setting the file position pointer at the specified bytes . fseek is a
function belonging to the ANCI C standard Library and included in the file stdio.h. Its
purpose is to change the file position indicator for the specified stream.
int fseek(FILE *stream_pointer, long offset, int
origin);
Argument meaning:

stream_pointer is a pointer to the stream FILE structure of which the position


indicator should be changed;

offset is a long integer which specifies the number of bytes from origin where the
position indicator should be placed;

origin is an integer which specifies the origin position. It can be:

SEEK_SET: origin is the start of the stream.

SEEK_CUR: origin is the current position.

SEEK_END: origin is the end of the stream.

/*
* Program to understand the use of fseek
function
*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct emprecord
{
char name[30];
int age;
float sal;
}emp;
void main()
{
int n;
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{
printf("/n error in opening file");
exit(1);
}
printf("enter the record no to be read");
scanf("%d",&n);
fseek(fp,(n-1)*sizeof(emp),0);
freed(&emp,sizeof(emp),1,fp);
printf("%s\t,emp.name);
printf("%d\t",emp.age);
printf("%f\n",emp.sal);
fclose(fp);
getch();
};