Sie sind auf Seite 1von 18

Last chapter explained about standard input and output devices handled by C programming language.

This chapter
we will see how C programmers can create, open, close text or binary files for their data storage.
A file represents a sequence of bytes, does not matter if it is a text file or binary file. C programming language
provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices.
This chapter will take you through important calls for the file management.

Opening Files
You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the
type FILE, which contains all the information necessary to control the stream. Following is the prototype of this
function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have one of the following
values:
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. Here your program will

start writing content from the beginning of the file.


a

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

r+

Opens a text file for reading and writing both.

w+

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

a+

Opens a text file for reading and writing both. It creates the file if it does not 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"

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This function actually,
flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The
EOF is a constant defined in the header file stdio.h.
There are various functions provide by C standard library to read and write a file character by character or in the form
of a fixed length string. Let us see few of the in the next section.

Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the
written character written on success otherwise EOF if there is an error. You can use the following functions to write a
null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on
success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format,
...) function as well to write a string into a file. Try the following example:
Make sure you have /tmp directory available, if its not then before proceeding, you must create this directory on your
machine.
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines
using two different functions. Let us read this file in next section.

Reading a File
Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or
in case of any error it returns EOF. The following functions allow you to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into
the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum
number of characters, then it returns only the characters read up to that point including new line character. You can
also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the
first space character encounters.
#include <stdio.h>
main()
{
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
When the above code is compiled and executed, it reads the file created in previous section and produces the
following result:
1 : This
2: is testing for fprintf...
3: This is testing for fputs...
Let's see a little more detail about what happened here. First fscanf() method read just This because after that it
encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally last
call fgets() read second line completely.

Binary I/O Functions


There are following two functions, which can be used for binary input and output:
size_t fread(void *ptr, size_t size_of_elements,
size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements,
size_t number_of_elements, FILE *a_file);

Both of these functions should be used to read or write blocks of memories - usually arrays or structures.

C File Handling - File Pointers


C communicates with files using a new datatype called a file pointer. This type is
defined within stdio.h, and written as FILE *. A file pointer called output_file is
declared in a statement like
FILE *output_file;

Opening a file pointer using fopen

Your program must open a file before it can access it. This is done using the fopen
function, which returns the required file pointer. If the file cannot be opened for any
reason then the value NULL will be returned. You will usually use fopen as follows
if ((output_file = fopen("output_file", "w")) == NULL)
fprintf(stderr, "Cannot open %s\n", "output_file");

fopen takes two arguments, both are strings, the first is the name of the file to be
opened, the second is an access character, which is usually one of:

"r" Open file for reading


"w" Open file for writing
"a" Open file for appending

Closing a file using fclose

The fclose command can be used to disconnect a file pointer from a file. This is
usually done so that the pointer can be used to access a different file. Systems have a
limit on the number of files which can be open simultaneously, so it is a good idea to
close a file when you have finished using it. This would be done using a statement
like
fclose(output_file);

If files are still open when a program exits, the system will close them for you.
However it is usually better to close the files properly.

Input and Output using file pointers

Having opened a file pointer, you will wish to use it for either input or output. C
supplies a set of functions to allow you to do this. All are very similar to input and
output functions that you have already met.
Character Input and Output with Files

This is done using equivalents of getchar and putchar which are called getc and putc.
Each takes an extra argument, which identifies the file pointer to be used for input or
output.

putc(c, fp)
getc (fp)
Formatted Input Output with File Pointers

Similarly there are equivalents to the functions printf and scanf which read or write
data to files. These are called fprintf and fscanf.
The functions are used in the same way, except that the fprintf and fscanf take the
file pointer as an additional first argument.
fprintf ( output_file, "This is a listing file\n" ) ;
fscanf ( input_file, "%d", &counter ) ;

Formatted Input Output with Strings

These are the third set of the printf and scanf families. They are called sprintf and
sscanf.
sprintf
puts formatted data into a string which must have sufficient space allocated to
hold it. This can be done by declaring it as an array of char. The data is
formatted according to a control string of the same form as that for p rintf.
sscanf

takes data from a string and stores it in other variables as specified by the
control string. This is done in the same way that scanf reads input data into
variables. sscanf is very useful for converting strings into numeric v values.

Whole Line Input and Output using File Pointers

Predictably, equivalents to gets and puts exist called fgets and fputs. The
programmer should be careful in using them, since they are incompatible with gets
and puts. gets requires the programmer to specify the maximum number of
characters to be read. fgets and fputs retain the trailing newline character on the line
they read or write, wheras gets and puts discard the newline.
When transferring data from files to standard input / output channels, the simplest
way to avoid incompatibility with the newline is to use fgets and fputs for files and
standard channels too.
For Example, read a line from the keyboard using
fgets(data_string, 80, stdin);

and write a line to the screen using


fputs(data_string, stdout);

EOF, The End of File Marker

EOF is a character which indicates the end of a file. It is returned by read commands
of the getc and scanf families when they try to read beyond the end of a file.
When you are reading from a file it is useful to be able to check whether or not you
have reached the end, without just failing to read. The function feofcan be used to find
out if you have hit the end :
if ( feof (input_file ) ) printf ( "BANG!\n" ) ;

This function returns the value 0 if the end of the file has not been reached, and
another value if it has. It takes a FILE pointer as a parameter.

C Programming Files
In C programming, file is a place on disk where a group of related data is stored.

Why files are needed?


When the program is terminated, the entire data is lost in C programming. If you want to keep large
volume of data, it is time consuming to enter the entire data. But, if file is created, these information
can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. In this tutorial, you will learn
to handle standard I/O(High level file I/O functions) in C.
High level file I/O functions can be categorized as:
1. Text file
2. Binary file

File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file

Working with file


While working with file, you need to declare a pointer of type file. This declaration is needed for
communication between file and program.
FILE *ptr;

Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard
I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\program.txt","w");
/* --------------------------------------------------------- */
E:\\cprogram\program.txt is the location to create file.
"w" represents the mode for writing.
/* --------------------------------------------------------- */

Here, the program.txt file is opened for writing mode.

Opening Modes in Standard I/O

File Mode

Meaning of Mode

During Inexistence of file

Open for reading.

If the file does not exist, fopen() returns


NULL.

Open for writing.

If the file exists, its contents are


overwritten. If the file does not exist, it
will be created.

Open for append. i.e,


Data is added to end of
file.

If the file does not exists, it will be


created.

r+

Open for both reading


and writing.

If the file does not exist, fopen() returns


NULL.

w+

Open for both reading


and writing.

If the file exists, its contents are


overwritten. If the file does not exist, it
will be created.

a+

Open for both reading


and appending.

If the file does not exists, it will be


created.

Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library
function fclose().
fclose(ptr); //ptr is the file pointer associated with file to be closed.

The Functions fprintf() and fscanf() functions.


The functions fprintf () and fscanf () are the file version of printf () and fscanf () . The only
difference while using fprintf () and fscanf () is that, the first argument is a pointer to the structure
FILE

Writing to a file
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}

This program takes the number from user and stores in file. After you compile and run this program,
you can see a text file program.txt created in C drive of your computer. When you open that file,
you can see the integer you entered.
Similarly, fscanf () can be used to read data from file.

Reading from file


#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1);
/* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}

If you have run program above to write in file successfully, you can get the integer back entered in
that program using this program.
Other functions like fgetchar () , fputc () etc. can be used in similar way.

Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary
file.

If a large amount of numerical data it to be stored, text mode will be insufficient. In such case
binary file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from
file and writing to file.

Opening modes of binary files


Opening modes of binary files are rb , rb + , wb , wb + , ab and ab + . The only difference between
opening modes of text and binary files is that, b is appended to indicate that, it is binary file.

Reading and writing of a binary file.


Functions fread () and fwrite () are used for reading from and writing to a file on the disk
respectively in case of binary files.
Function fwrite() takes four arguments, address of data to be written in disk, size of data to be
written in disk, number of such type of data and pointer to the file where you wa nt to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);

Function fread () also take 4 arguments similar to fwrite () function as above.

File handling
In any programming language it is vital to learn file handling techniques. Many
applications will at some point involve accessing folders and files on the hard drive.
In C, a stream is associated with a file. Special functions have been designed for
handling file operations. Some of them will be discussed in this chapter. The header
file stdio.h is required for using these functions.
Opening a file

Before we perform any operations on a file, we need to open it. We do this by using a
file pointer. The type FILE defined in stdio.h allows us to define a file pointer. Then
you use the function fopen() for opening a file. Once this is done one can read or write
to the file using the fread() or fwrite() functions, respectively. The fclose() function is
used to explicitly close any opened file.
Taking the preceding statements into account let us look at the following example
program :

Program 13.1
#include <stdio.h>
main ()
{
FILE *fp;
fp = fopen("data.txt", "r");
if (fp == NULL) {
printf("File does not exist,
please check!\n");
}
fclose(fp);
}

fopen()
Let us first discuss fopen(). This function accepts two arguments as strings. The first
argument denotes the name of the file to be opened and the second signifies the mode
in which the file is to be opened. The second argument can be any of the following:
File Mode

Description

Open a text file for reading

Create a text file for writing, if it exists, it is overwritten.

Open a text file and append text to the end of the file.

rb

Open a binary file for reading

wb

Create a binary file for writing, if it exists, it is overwritten.

ab

Open a binary file and append data to the end of the file.
Table 13.1

fclose()
The fclose() function is used for closing opened files. The only argument it accepts is
the file pointer.

If a program terminates, it automatically closes all opened files. But it is a good


programming habit to close any file once it is no longer needed. This helps in better
utilization of system resources, and is very useful when you are working on numerous
files simultaneously. Some operating systems place a limit on the number of files that
can be open at any given point in time.
fscanf() and fprintf()
The functions fprintf() and fscanf() are similar to printf() and scanf() except that these
functions operate on files and require one additional and first argument to be a file
pointer.
Program 13.2
#include <stdio.h>
main ()
{
FILE *fp;
float total;
fp = fopen("data.txt", "w+");
if (fp == NULL) {
printf("data.txt does not exist, please check!\n");
exit (1);
}
fprintf(fp, 100);
fscanf(fp, "%f", &total);
fclose(fp);
printf("Value of total is %f\n", total);
}

getc() and putc()


The functions getc() and putc() are equivalent to getchar() and putchar() functions
which you studied in Chapter 12 on Input and Output, except that these functions
require an argument which is the file pointer. Function getc() reads a single character
from the file which has previously been opened using a function
like fopen(). Function putc() does the opposite, it writes a character to the file
identified by its second argument. The format of both functions is as follows :
getc(in_file);
putc(c, out_file);
Note: The second argument in the putc() function must be a file opened in either write
or append mode.

Program 13.3
#include <stdio.h>
main ()
{
char in_file[30], out_file[30];
FILE *fpin, *fpout;
int c;
printf("This program copies the source file to the destination file
\n\n");
printf("Enter name of the source file :");
scanf("%30s", in_file);
printf("Enter name of the destination file :");
scanf("%30s", out_file);
if((fpin=fopen(in_file, "r")) == NULL)
printf("Error could not open source file for
reading\n");
else if ((fpout=fopen(out_file, "w")) == NULL)
printf("Error could not open destination file for
reading\n");
else
{
while((c =getc(fpin)) != EOF)
putc(c, fpout);
printf("Destination file has been copied\n");
}
}

Binary stream input and output


The functions fread() and fwrite() are a somwhat complex file handling functions used
for reading or writing chunks of data containing NULL characters ('\0') terminating
strings.
The function prototype of fread() and fwrite() is as below :
size_t fread(void *ptr, size_t sz, size_t n, FILE *fp)
size_t fwrite(const void *ptr, size_t sz, size_t n, FILE *fp);
You may notice that the return type of fread() is size_t which is the number of items
read. You will understand this once you understand how fread() works. It
reads n items, each of size sz from a file pointed to by the pointer fp into a buffer
pointed by a void pointer ptr which is nothing but a generic pointer.
Function fread() reads it as a stream of bytes and advances the file pointer by the
number of bytes read. If it encounters an error or end-of-file, it returns a zero, you
have to use feof() or ferror() to distinguish between these two. Function fwrite() works
similarly, it writes n objects of sz bytes long from a location pointed to byptr, to a file
pointed to by fp, and returns the number of items written to fp.

Let us rewrite program 13.3 using fread() and fwrite() functions .


Program 13.4
#include <stdio.h>
#define MAX_SIZE 1024
main ()
{
FILE *fp, *gp;
char buf[MAX_SIZE];
int i, total = 0;
if ((fp = fopen("data1.txt", "r") ) == NULL)
printf("Error in data1.txt file \n");
else if ((gp=fopen("data2.txt", "w")) == NULL)
printf("Error in data2.txt file \n");
else
{
while(i=fread(buf, 1, MAX_SIZE, fp))
{
fwrite(buf, 1, MAX_SIZE, gp);
total +=i;
}
printf("Total is %d\n", total);
}
fclose(fp);
fclose(gp);
}

ftell()
Functions ftell() and fseek() are important in a program performing file
manipulations. Function ftell() returns the current position of the file pointer in a
stream. The return value is 0 or a positive integer indicating the byte offset from the
beginning of an open file. A return value of -1 indicates an error. Prototype of this
function is as shown below :
long int ftell(FILE *fp);
fseek()
This function positions the next I/O operation on an open stream to a new position
relative to the current position.
int fseek(FILE *fp, long int offset, int origin);
Here fp is the file pointer of the stream on which I/O operations are carried
on, offset is the number of bytes to skip over. Theoffset can be either positive or

negative, denting forward or backward movement in the file. origin is the position in
the stream to which the offset is applied, this can be one of the following constants :
SEEK_SET : offset is relative to beginning of the file
SEEK_CUR : offset is relative to the current position in the file
SEEK_END : offset is relative to end of the file
Program 13.5
#include <stdio.h>
#include <stdlib.h>
char buffer[11];
int position;
main ()
{
FILE *file_ptr;
int num;
if ((file_ptr = fopen("test_file", "w+f 10"))
== NULL)
{
printf("Error opening test_file \n");
exit(1);
}
fputs("1111111111", file_ptr);
fputs("2222222222", file_ptr);
if ( (position = fseek(file_ptr, 10, SEEK_SET)) != 0)
{
printf("Error in seek operation: errno \n");
exit(1);
}
num = 11;
fgets(buffer, num, file_ptr);
printf("The record is %s\n", buffer);
fclose(file_ptr);
}

The output from the preceding program will be


The record is 2222222222.

Das könnte Ihnen auch gefallen