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

Chapter 13

Files in C
Introduction
 Need for files in C
Usually programs consume a large amount of data and
generates information. Now the situation arises where in
we cannot enter the data repeatedly and also we need to
store the generated information permanently.

So we need a mechanism which allows to retrieve the


input data from secondary storage and also saves the
generated output onto secondary storage for future
purposes.

In C, the mechanism is called FILE


A File is a collection of related data which is stored in a
secondary storage device such as a disk, cd etc.

There are 2 types of Files


1. Text File // Contains human readable information
2. Binary File // Contains binary information 0’s and 1’s

A FILE is a structure which is defined in the header file


<stdio.h>. In order to access a file and use it, we make
use of a file pointer.
Note that the word FILE is
FILE *ptr_name; case sensitive.
file File are not the file
structure defined in stdio.h
and will generate an error
 States of a File: A File can have 3 states
1. Read
2. Write
3. Error

Modes of a File: By mode we mean, the method in


which the file is accessed. There are 6 modes for a file.

Binary File Text File


1. rb 1. r
2. wb 2. w
Note that the binary file
3. ab 3. a
mode has the character b at
4. r+b 4. r+
the end of the mode
5. w+b 5. w+
6. a+b 6. a+
Modes of a file Continued
Modes Description
r Opens an existing text file for reading purpose.
Error if file does not exist.
w Opens a text file for writing, if it does not exist then a new file is
created. Here content is added from the beginning of the file.
Original contents of the file is lost or overwritten.
a Opens a text file for writing in appending mode, if it does not exist then
a new file is created. Here content is appended at the end of the the
existing file content. No information is lost.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncates 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.
fopen() function
 The fopen() function is used to open a file with the required
mode. It makes use of a file pointer.

The syntax for the fopen() is


FILE *fptr;
fptr = fopen( “ file_name”, ” mode”);

 If the fopen() is successful, it returns the File pointer


 If the fopen() is unsuccessful, it return NULL

Example : FILE *ptr1, *ptr2, *ptr3;


ptr1 = fopen(“hello.txt”, ”r”);
ptr2 = fopen(“hi.txt”, ”w”);
ptr3 = fopen(“bye.txt”, ”a”);
fclose() function
 The fclose() function is used to close a file. It also
makes use of a file pointer.

The syntax for the fclose() is


fclose(file_Pointer);
 The fclose( ) function returns zero on success
 If there is an error in closing the file it returns EOF .

The EOF is a constant defined in the header file stdio.h.


It is used to indicate the End Of File.
Functions to read from a file
 getc() and getw() functions are used to read the contents
of a file using a file pointer which has been opened using
the fopen() function in read mode.

 The syntax for the getc() is


ch = getc( fptr); getc() is used to
read a single
character from a
 The syntax for the getw() is file.

num = getw( fptr); getw() is used to


read a integer
ch is a variable of type char value from a file
num is a variable of type int.
Functions to write into a file
 putc() and putw() functions are used to write into a file
the contents, using a file pointer which has been opened
using the fopen() function in write mode.

 The syntax for the putc() is


putc( ch, fptr); putc() is used to
write a single
character into a
 The syntax for the getw() is file.

putw( num, fptr); putw() is used to


write a integer
See that the file pointer is value into a file
the 2nd argument of the
functions.
C program to read and write from a file
#include<stdio.h>
main( )
{ FILE *fp1,*fp2;
char ch;
fp1 = fopen(“hello.txt", "r"); // creating file pointers and using fopen()
fp2 = fopen(“ hi.txt”, ”a”);
if (fp1 == NULL) if file cannot be opened
printf("File doesn't exist\n"); then fopen() returns a
else NULL pointer
do { ch = getc(fp1); // get one character from the file hello.txt
putc(ch, fp2); // write one character into the file hi.txt
} while (ch != EOF); // repeat until EOF (end of file)
fclose(fp1);
fclose(fp2);
}
Program to remove repeated consecutive
characters
Input file content
Ram ssite 11 43 % %%%**(()55tyr
djdf kdfd kkp

Output file
Ram site 1 43 % %*()5tyr
djdf kdfd kp
#include<stdio.h>
void main( )
{ FILE *fpt1,*fpt2;
char ch, chp;
fpt1 = fopen("hi", "r");
fpt2 = fopen("hio","w");
if (fpt1 == NULL)
printf("File doesn't exist\n");
else
{ chp = '*';
while ( (ch = getc(fpt1)) != EOF)
{ if(ch != chp) putc(ch,fpt2);
chp=ch;
}
}
fclose(fpt1);
fclose(fpt2);
}
fscanf() and fprintf() functions
 The previous file I/O functions can handle only a
single character or integer value at a time. Thus we
have fscanf() and fprintf() functions which can handle
larger and varied data at a time.
 The fscanf() can make use of the stdin pointer to read
values from the standard input ( i.e keyboard).
 The fprintf() can display the contents of the file to the
standard output(i.e monitor) using the stdout pointer.
 The syntax for the functions are
fscanf( ptr, control_ string, argument_list);
fprintf( ptr, control_ string, argument_list);
Write a C progam to read
Employee No.(0 to exit), Name,
Designation, Basic salary and
Grade of Employees and store
this data in a file "emp.dat“.
Display the employee list from
this file.
Employee No.(0 to exit) : 11
Name : Rama Rao M
Desigation : Manager
Basic salary : 34000
Grade :B
Employee No.(0 to exit) : 88
Name : Ajith Holla
Desigation : Asst. Mgr
Basic salary : 24000
Grade :C
Employee No.(0 to exit) : 665
Name : Kiran Ram Yadla
Desigation : Sr. Manager
Basic salary : 45000
Grade :A
Employee No.(0 to exit) : 0
Emp No. Name Designation Grade Basic
------- ----------- ----------- ----- ----- --------
11 Rama Rao M Manager B 34000
88 Ajith Holla Asst. Mgr C 24000
665 Kiran Ram Yadla Sr. Manager A 45000
#include <stdio.h>
main()
{ int empno, basic, da, hra, gs, pf, ptax, ns;
FILE *emp;
char desig[15], name[25], grade;
emp = fopen("emp.dat","w");
while(1)
{ printf (" Employee No.(0 to exit) : ");
scanf("%d", &empno);
if(empno==0) break;
printf("Name : ");
scanf(" %[^\n]",name);
printf("Desigation : ");
scanf(" %[^\n]",desig);
printf("Basic salary : ");
scanf("%d",&basic);
printf("Grade :");
scanf(" %c",&grade);
fprintf(emp,"%d %s\n%c %d %s\n", empno, name,
grade, basic, desig);
}
fclose (emp);
emp =fopen("emp.dat","r"); //same file is opened again
// with same file pointer variable
printf("Emp No. Name Designation Grade
Basic\n");
printf("------- ----------- ----------- ----- -----
\n");
while( !feof(emp) )
{ fscanf(emp,"%d %[^\n]\n%c %d %[^\n]\n",
&empno, name, &grade, &basic, desig);
printf(" %3d\t %-20s %-15s%c %5d\n",
empno, name, desig, grade, basic);
}
}
Standard Error
Standard error (stderr)is a file pointer where we display error
messages.
fprintf(stderr, "Can't open input file !\n");

Standard error is normally associated with the same place as


standard output. However, redirecting standard output does
not redirect standard error.

standard input is normally associated


with the keyboard and
standard output with the screen
Program to use fprintf ()and fscanf() functions with stdin and stdout

#include <stdio.h>
#include <stdlib.h>
main()
{ FILE *fp; char name[80]; int age, n, i=0;
if((fp=fopen("test.txt","w"))==NULL)
{ printf("Cannot open file.\n");
exit(1);
}
printf("How many employees");
scanf("%d",&n);
while(i++<n)
{ printf("Enter the name and age: ");
fscanf(stdin,"%s%d",name,&age);//read from kboard
fprintf(fp,"%s %d",name,age);//write to file
}
fclose(fp);
if((fp=fopen("test.txt","r"))==NULL)
{ printf("Cannot open file.\n");
exit(1);
}
while( !feof(fp))
{ fscanf(fp,"%s%d",name,&age);// read from file
fprintf(stdout,"%s %d\n",name,age);
// print on screen
}
}
Errors which occur during file I/0 operations
Trying to read beyond end-of-file (EOF)
Trying to use a file that has not been
opened
Perform operation on file not permitted by
the fopen mode i.e. attempting a write using
a file pointer opened using a read mode
Open a file with an invalid filename
Attempting a write to a write-protected file
Error Handling in Files
feof() takes file-pointer as input.
 returns nonzero (true) if all data read
 returns zero (false) otherwise
if(feof(fp))
printf(“End of data\n”); feof() is a function
whereas EOF is a constant

ferror() takes file-pointer as input.


 returns nonzero (true) integer if error detected
 returns zero (false) if no error is detected
if ( ferror(fp) != 0 )
printf(“An error has occurred\n”);
fputs( )
int fputs ( const char * str, FILE * stream );
Write string to stream
Writes the string pointed by str to the stream.

The function begins copying from the address specified


(str) until it reaches the terminating null character ('\0').
This terminating null-character is not copied to the
stream.
Notice that fputs not only differs from puts in that the
destination stream can be specified, but also fputs does
not write additional characters, while puts appends a
newline character at the end automatically.
fgets()
char * fgets ( char * str, int num, FILE * stream );
Get string from the file
Reads characters from file and stores them as a C string into str
until (num-1) characters have been read or either a newline or
the end-of-file is reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered
a valid character by the function and included in the string copied
to str.

A terminating null character is automatically appended after the


characters copied to str.

Notice that fgets is quite different from gets: not


only fgets accepts a file pointer argument, but also allows to specify
the maximum size of str and includes in the string any ending
newline character.
#include <stdio.h>
int main()
{ FILE * pFile;
char mystring [100];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) printf("Error opening file");
else
while(fgets (mystring, 10, pFile) != NULL )
puts(mystring);
fclose (pFile);
}
Input file myfile.txt
NITK SURATHKAL MANGALORE
575025
NIT
This is a long sentence which may not fit in all strings.
This is the end
Bye
Output
NITK SURA
THKAL MAN
GALORE

575025

NIT

This is a
long sen
tence whi
ch may no
t fit in
all strin
gs.

This is t
he end

Bye
#include <stdio.h>
int main()
{ FILE * pFile;
char mystring [100];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) printf("Error opening file");
else
while(fgets (mystring, 20, pFile) != NULL )
puts(mystring);
fclose (pFile);
}
Output
NITK SURATHKAL MANG
ALORE

575025

NIT

This is a long sent


ence which may not
fit in all strings.

This is the end

Bye
#include <stdio.h>
int main()
{ FILE * pFile;
char mystring [100];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) printf("Error opening file");
else
while(fgets (mystring, 10, pFile) != NULL )
printf(“%s”,mystring);
fclose (pFile);
}
output
NITK SURATHKAL MANGALORE
575025
NIT
This is a long sentence which may not fit in all strings.
This is the end
Bye
Random access to files
Till now we have seen a sequential manner in which we can
access files, which is either from the beginning of the
file(read/write modes) or from the end of the file(append
modes).
The question which arises is how to jump to a given position
(byte number) in a file without reading all the previous data?

C provides us 3 functions which help us to achieve the same.


They are
1. ftell()
2. rewind()
3. fseek()
 The fseek() has three arguments which are given in the order as
follows
fseek (file-pointer, offset, position);
where position: 0 (beginning), 1 (current), 2 (end)
offset: number of locations to move from position

fseek(fptr,-5, 1); // move 5 positions behind from the current


fseek(fptr,3, o); // move 3 positions forward from the begin

 ftell(fp) returns current byte position in file

rewind(fp) resets position to start of file


Command line arguments
Till date we have seen how we can give inputs to a C program
using scanf(), getchar(), gets() functions.
But we can also provide these inputs in the form of
arguments from the command line itself.
E.g. cc prog.c name1 name2 ….
This is done by having arguments to the main function
main( int argc, char *argv[] )
argc – gives count of number of arguments
char *argv[] defines an array of pointers to character

here argv[0] is the program name and argv[1],


argv[argc -1]etc gives the arguments as strings
Program to demonstrate command line arguments
#include<stdio.h>
main( int argc, char *argv[ ] )
{ while(argc>0) // Display all arguments in
// reverse order
{ printf("%s\n",argv[argc-1]);
argc--;
}
}
OUTPUT

$ cc program.c
$ ./a.out I study @ NITK
NITK
@
study
I
$
Write a program to display
the factorial of a given integer
using command line
arguments.
cmdlnfct 3
Fact 6
cmdlnfct
Enter the integer 4
Fact 24
/* Command line arguments for Factorial */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main(int argn,char *argc[ ])
{ int n, f=1;
if (argn==1) /*If The input number is not given at command
line */
{ printf("Enter the integer");
scanf("%d",&n);
}
else n= atoi(argc[1]); /* convert string to integer */
while(n) f *=n--;
printf("Fact %d",f);
}
Why do we require Files in C ? Also explain in detail
the different types of Files.
Explain the fopen() with the different modes it utilizes
Write short notes on the following file functions
fclose() getc() putc() getw() putw()
Write short notes on the File random access functions
available in C
What are Command Line arguments? Explain with a
suitable program

You might also like