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

UAA 105 M S Prasad: Aisst

A file is a collection of bytes stored on a secondary storage device like a disk. There are two kinds of files: text files and binary files. Text files can be read sequentially in the forward direction only, while binary files contain raw bytes and can be accessed randomly. In C, files must be opened, read from or written to, and closed. Common file I/O functions include fopen(), fclose(), getc(), putc(), fprintf(), and fscanf().

Uploaded by

Sai Shubhankar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

UAA 105 M S Prasad: Aisst

A file is a collection of bytes stored on a secondary storage device like a disk. There are two kinds of files: text files and binary files. Text files can be read sequentially in the forward direction only, while binary files contain raw bytes and can be accessed randomly. In C, files must be opened, read from or written to, and closed. Common file I/O functions include fopen(), fclose(), getc(), putc(), fprintf(), and fscanf().

Uploaded by

Sai Shubhankar
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

AISST

UAA 105

M S Prasad
File Handling in C

A file is a collection of bytes stored on a secondary storage device, which is generally a disk of
some kind. The collection of bytes may be interpreted, for example, as characters, words, lines,
paragraphs and pages from a textual document; fields and records belonging to a database; or
pixels from a graphical image. There are two kinds of files that is text files and binary files.
Text Files
A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened
for only one kind of operation (reading, writing, or appending) at any given time.
Binary Files
A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a
byte and a character are equivalent. No special processing of the data occurs and each byte of data
is transferred to or from the disk unprocessed. C Programming Language places no constructs on
the file, and it may be read from, or written to, in any manner chosen by the programmer.
Opening a file:
The general format of the function used for opening a file is
FILE *fp;
fp=fopen(filename,mode); /* FILE is a reserved word needs to be used as shown always. It
is a data type defined in stdio.h file.*/
The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier,
FILE is a structure that is defined in the I/O Library. The second statement opens the file named
filename and assigns an identifier to the FILE type pointer fp. fopen() contain the file name and
mode (the purpose of opening the file).
r is used to open the file for read only.
w is used to open the file for writing only.
a is used to open the file for appending data to it.
Closing a File
A file must be closed as soon as all operations on it have been completed. This would close the file
1

associated with the file pointer. The input output library supports the function to close a file.
Syntax to close file

fclose(filepointer);
Example
#include
void main(void)
{
FILE *myfile;
char c;
myfile = fopen("firstfile.txt", "r");
if (myfile == NULL) printf("File doesn't exist\n");
else {
do {
c = getc(myfile);
putchar(c);
} while (c != EOF);
}
fclose(myfile);
}
File operation functions in C:
Function Name
Operation
fopen()
Creates a new file. Opens an existing file.
Fclose
Closes a file which has been opened for use
getc()
Reads a character from a file
putc()
Writes a character to a file
fprintf()
Writes a set of data values to a file
fscanf()
Reads a set of data values from a file
getw()
Reads a integer from a file
putw()
Writes an integer to the file
fseek()
Sets the position to a desired point in the file
ftell()
Gives the current position in the file
rewind()
Sets the position to the beginning of the file
This table shows all of the combinations including both text and binary files. Generally you either
read from or write to a text file, but not both at the same time.
With a binary file you can both read and write to the same file. The table below shows what you
can do with each combination.

Mode Type of file Read Write Create Truncate


r text Read
rb+ binary Read
r+ text Read Write
r+b binary Read Write
rb+ binary Read Write
w text Write Create Truncate
wb binary Write Create Truncate
w+ text Read Write Create Truncate
w+b binary Read Write Create Truncate
wb+ binary Read Write Create Truncate
a text Write Create
ab binary Write Create
a+ text Read Write Create
a+b binary Write Create
ab+ binary Write Create

In my experience with files, unless you are just creating them (use "wb") or reading them (use
"rb" ) you can get away with using "w+b". This lets you create a file from scratch,

File I/O Routines


getc() and putc()
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).
Thus the statement :
c = getc(fp);
reads the next character from the file referenced by fp and the statement
putc(c,fp);

writes the character c into file referenced by fp.

/* Example to Display contents of a file on screen */


#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
fp = fopen( prog.c, r );
c = getc( fp ) ;
while ( c != EOF ) /* EOF is a defined word for end of File */
{
putchar( c );
c = getc ( fp );
}
fclose( fp );
}
3

In this program, we open the file prog.c for reading. We then read a character
from the file. This file must exist for this program to work. If the file is empty,
we are at the end, so getc returns EOF a special value to indicate that the end
of file has been reached. (Normally -1 is used for EOF)
The while loop simply keeps reading characters from the file and displaying
them, until the end of the file is reached.The function fclose is used to close
the file i.e. indicate that we are finished processing this file.
We could reuse the file pointer fp by opening another file.

RULE: Always check when opening files, that fopen succeeds in


opening the files appropriately.
Other File I/O

Prototypes

int getc (FILE *fp) :Returns the next character from


`
`fp', or EOF on error or end-of-file.
int putc (int c, FILE *fp) : Write the character c to the
file `fp', returning the character written, or EOF on
error.
int fscanf (FILE *fp, char *format, ...) Like scanf,
except input is taken from the file fp.
int fprintf (FILE *fp, char *format, ...) Like printf,
except output is written to the file fp.
char *fgets (char *line, int n, FILE *fp) Gets the next
line of input from the file fp, up to `n-1' characters in
length.The newline character is included at the end
of the string, and a null is appended. Returns
`line' if successful, else NULL if end-of-file
or other error.
int fputs (char *line, FILE *fp) Outputs the string
`line' to the file fp. Returns zero is successful, EOF
if not.
When you have finished with a file, you should close it
with 'fclose':
int fclose (FILE *fp) : Closes the file 'fp', after
flushing any buffers. This function is automatically
called for any open files by the operating fflush(FILE*fp)
Flushesanybuffersassociatedwiththefile'fp'.

To check the status of a file, the following functions


can be called:
int feof (FILE *fp)
file is read.

Returns non-zero when an end-of-

int ferror (FILE *fp) Returns non-zero when an error has


occurred, unless cleared by clearerr.
void clearerr (FILE *fp) Resets the error and end-of-file
statuses.
int fileno (FILE *fp) returns the integer file descriptor
associated with the file (useful for low-level I/O).
Example: Write a program to display file contents 20 lines at a time. The
program pauses after displaying 20 lines until the user presses either Q to quit
or Return to display the next 20 lines. (The Unix operating system has a
command called more to do this ) we read the filename from user and open it
appropriately. We then process the file:
read character from file
while not end of file and not finished do
begin
display character
if character is newline then
linecount = linecount + 1;
if linecount == 20 then
begin
linecount = 1 ;
Prompt user and get reply;
end
read next character from file
end
/* display.c: File display program */
/* Prompt user for file and display it 20 lines at a time*/
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c , linecount;
char filename[40], reply[40];
5

printf(Enter file name: );


gets( filename );
fp = fopen( filename, r );

/* open for reading */

if ( fp == NULL )
/* check does file exist etc */
{
printf(Cannot open %s for reading \n, filename );
exit();
/* terminate program */
}
linecount = 1 ;
reply[0] = \0 ;
c = getc( fp ) ;
/* Read 1st character if any */
while ( c != EOF && reply[0] != Q && reply[0] != q)
{
putchar( c ) ;
/* Display character */
if ( c == \n )
linecount = linecount+ 1 ;
if ( linecount == 20 )
{
linecount = 1 ;
printf([Press Return to continue, Q to quit]);
gets( reply ) ;
}
c = getc ( fp );
}
fclose( fp );
}
Writing to Files
The previous programs have opened files for reading and read characters from
them.
To write to a file, the file must be opened for writing e.g.
fp = fopen( fname, w );
If the file does not exist already, it will be created. If the
be overwritten! So, be careful when opening files for
destroy a file unintentionally. Opening files for writing can
create a file in another users directory where you do not
not be allowed and fopen will fail.

file does exist, it will


writing, in case you
also fail. If you try to
have access you will

Random File access


Prototypes available are : fseek () , rewind, () , ftell()
6

fseek ( file pointer, long offset , int specifier );


file pointer : Points to the file for Random access .
offset : defines from where to start
Specifier : specifies beginning , current position of the pointer.
Example
long n ;
fseek( fp , 0l, 0) : /* go to start of the file . offset being 0 and also specifier
0)
fseek ( fp, n , 0) / 8 go to n th byte of the file from start.
fseek( fp, n , 1 ) / * skip ahead n th byte from current position)
fseek (fp , -n , 2 ) / * nth byte before the end of file */
rewind : moves the internal file pointer
equivalent to writing fseek ( fp, 0l , 0)

to the beginning of the

file. It is

ftell : takes a file pointer and returns a long containing the current offset in
the file and next byte .
Read & write block Files
Fread ( pointer to arrays first element , size in bytes of element , no
of elements , file pointer)
fread( ( void *) a , size of (int), max , fp ); FILE * fp ;
Similiarly for writing also : fwrite ( ( void *) a , size of ( int) , max, fp);
____________________________________________________
Passing Arguments from Command line
Accessing the command line arguments is a very useful facility. It enables you
to provide commands with arguments that the command can use .
To access these arguments from within a C program, you pass parameters to
the function main(). The use of arguments to main is a key feature of many C
programs.
The declaration of main looks like this:
7

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


This declaration states that
1. main returns an integer value (used to determine if the program
terminates successfully)
2. argc is the number of command line arguments including the command
itself i.e argc must be at least 1
3. argv is an array of the command line arguments
The declaration of argv means that it is an array of pointers to strings (the
command line arguments). By the normal rules about arguments whose type is
array, what actually gets passed to main is the address of the first element of
the array. As a result, an equivalent (and widely used) declaration is:
int main (int argc, char **argv)
When the program starts, the following conditions hold true:
argc is greater than 0.
argv[argc] is a null pointer.
argv[0], argv[1], ..., argv[argc-1] are pointers to strings with
implementation defined
meanings.
argv[0] is a string which contains the programs name, or is an empty
string if the name
isnt available. Remaining members of argv are the
programs arguments.
Example: Echoes its arguments to the standard output
/* print_args.c: Echo command line arguments */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int i = 0 ;
int num_args ;
num_args = argc ;
while( num_args > 0)
{
printf(%s\n, argv[i]);
i++ ;
num_args--;
}
} /*If the name of this program is print_args, an example of its execution is as
follows:
% print_args hello goodbye solong ;print_args hello
goodbye
8

solong
%
---------------------------------------------------------------------------------------------------

You might also like