Professional Documents
Culture Documents
OPENING A FILE:
1. File name
2. Data structure
3. Purpose
File name is a string of characters that make up a valid filename for the operating system.
It may contain two parts: a file name and optional period with extension.
Data structure of a file is deified as FILE in the library of standard I/O function
definitions. Therefore, all files should be declared as type FILE before they are used.
FILE is defined as data type.
When we open a file, we must specify what we want to do with the file. We may write
data to the file or read the already existing data.
General format/syntax:
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable the variable fp is a “pointer to the data type
FILE”.FILE is a structure that is defined in the the I/O library.
The second statement specifies the purpose of opening this file. Mode is used to specify
the purpose of opening a file.
When we are trying to open a file, one of the following things may happen:
1. Opens a file in write mode. It returns null if file could not be opened .If file exists
with some data then it will be overwritten.
2. When the purpose is ‘appending’ the file is opened with the current content .A file
with the specified name is created if the file does not exists.
3. Opens a file in read mode and sets pointer to the first character in the file. It returns
null if file does not exist.
FILE *p1,*p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);
The file data is opened for reading and results is opened for writing .In case , the
results file already exists then its contents are deleted otherwise it is opened as a
new file. The data file does not exist, an error will occur.
They include:
r+ The existing file is opened to the beginning for both reading and writing.
We can open and use a number of files at a time. This number however depends on
the system we use.
#include<stdlib.h>
void main()
FILE *fp;
fp=fopen(“a.txt”,”w+”);
fprintf(fp,”%s%d”,”data structure”,”1”);
fclose(fp);
The above example illustrates the fopen() which is used for writing and reading
purpose which is indicated by “w+” mode. The opened file is pointed by the pointer
fp that is fp is pointing to “a.txt”,which can be used for reading or writing. Content
data structure and the number 1 is written to the file a.txt .Opened file is closed using
fclose() function.
CLOSING A FILE:
A file must be closed as soon as all operations on it have been completed. This
ensures that all the information associated with the file is flushed out from the buffers
and links to the file are broken.
It also prevents may accidental misuse of the file. In case, there is a limit on the
number file that can be opened simultaneously in such cases closing some files helps
to opens other files which you want to use for some file operations.
When you open a file which is opened in one mode helps to open the same file in
different mode.
fclose() function closes the file that is being pointed by the file pointer.
Syntax:
Parameter:
Return value:
This method returns zero if the stream is successfully closed. On failure, EOF is
returned.
fclose(fp);
In the above example the file pointer fp is pointing to the opened file which is closed
using fclose().
If multiple files are opened then we need to close all the files.
Example:
#include<stdio.h>
#include<stdlib.h>
void main()
FILE *fp;
char ch;
fp=fopen(“m.txt”,”r”);
while((ch=getc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
The above example illustrates the use of fclose() function for closing opened file using
fopen().Here the file pointer fp is pointing to the file m.txt which is used for reading.
Each character from the file is read till the EOF file mark. Once the reading process
finishes file is closed using fclose().
7. With an example explain how to read stream or set of data from a file.
i)getc():
Is similar to getchar() .It is used to read a single character from a file that has been
opened in read mode.After reading the character, the function increments the associated
file pointer to point to the next character.
Syntax:
getc(File pointer);
The getc() function takes file pointer as its argument it indicates the stream on which the
operation is to be performed.
Return value:
This function returns the character that is been read and the read is will be placed into a
character variable.
When we use getc() the file pointer moves one character position .It reruns the end of file
marker EOF , when end of the file has been reached. Therefore, the reading should be
terminated when EOF is encountered.
Example:
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("bv.txt","r");
if(fp==NULL)
exit(0);
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
OUTPUT:
data structure
The above example illustrates the use of getc() function for reading the content of the file
bv.txt.The file bv.txt is opened in read mode. If the file pointer is pointing to a character
in the file then characters are read one by one using getc() function which takes file
pointer as its parameter. On failure fp contains NULL such cases error will be produced.
ii)putc():-
putc() function is used to write a single character specified by the argument char to the
specified stream and advances the position indicator for the stream.
Syntax:
Parameter:
This function takes two parameters. First parameter is the character to be written.
Second parameter is the file pointer which is the pointer to the FILE object that
identifies the stream where the character is to be written.
Return value:
The value returned by the putc() is the value of the character written. If an error occurs,
EOF is returned.
Example:
#include<stdio.h>
void main()
FILE *fp;
char ch;
fp=fopen("bv.txt","w");
while((ch=getchar())!='\n')
putc(ch,fp);
fclose(fp);
OUTPUT:
Programming
iii) getw():
This an integer oriented functions similar to getc() it is used to read an integer value
which is pointed by the file pointer.
Syntax :
It takes a single parameter which is the file pointer that read an integer value.
Return value:
This function returns the integer value from the file associated with the file pointer on
success and returns EOF on error.
Example:
#include<stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen("file.txt","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
printf("\nData in file...\n");
fclose(fp);
}
Output :
Data in file...
78
45
63
In the above example, Statement 1 will open an existing file file.txt in read mode and
statement 2 will read all the integer values upto EOF(end-of-file) reached.
putw():
The putw() function takes two arguments, first is an integer value to be written to the file
and second is the file pointer where the number will be written.
#include<stdio.h>
void main()
{
FILE *fp;
int num;
char ch='n';
fp = fopen("file.txt","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
do //Statement 2
{
printf("\nEnter any number : ");
scanf("%d",&num);
putw(num,fp);
}while(ch=='y'||ch=='Y');
fclose(fp);
}
Output :
In the above example, statement 1 will create a file named file.txt in write mode.
Statement 2 is a loop, which take integer values from user and write the values to the file.
/*Program to read data from keyboard , write it to a file called INPUT, again read
the same data from the INPUT file and display it on the screen*/
#include<stdio.h>
void main()
FILE *f1;
char c;
printf(“input data”);
f1=fopen(“INPUT”,”w”);
while((c=getchar())!=’\n’)
putc(c,f1);
fclose(f1);
f1=fopen(“INPUT”,”r”);
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}
OUTPUT:
Data Input
File handling
Data output:
File handling
The above example illustrates the use of getc() and putc() for reading and writing from
and to a file. We enter data from the keyboard till the user presses the Enter key(\n) and
entered character is written to file using putc().
The file INPUT is again reopened for reading. The program reads the character one at a
time using getc() and the character is displayed on the screen.
i)fscanf():
Syntax:
Parameter:
It takes three parameters first one is stream it can be file pointer which is pointing the
opened file or It can be the terminal that is the standard input device from which the data
is read in which case it is always stdin.
Second parameter specifies in which format data is to be read .The format specifier or
control string begins with % sign .The format specifier is used to specify the format of
the data that has to be obtained from the stream and stored in the memory locations
pointed by the additional arguments.
Third parameter is the address of the variable from which you want to read from the file
which is stored in the particular variable memory.
Each of this must point to an object of the type specified by their corresponding % tag
within format string in same order.
Return value:
fscanf() function always returns an integer value that is the number of data that has been
read on failure it returns zero.
/*C program to create a file that contains at least 5 records which consists of Book
No., Book Name, Author, Publisher, and price*./
#include<stdio.h>
#include<ctype.h>
int main()
{
FILE *f;
int bno,i,n;
char bname[50],author[50],publisher[50];
float price;
printf("Enter 5 records\n");
f=fopen("out.txt","w");
if(f==NULL)
printf("can not open a file\n");
else
{
for(i=0;i<5;i++)
{
printf("Enter bookno,bookname,author,publisher and price");
scanf("%d%s%s%s%f",&bno,bname,author,publisher,&price);
fprintf(f,"%d\t%s\t%s\t%s\t%f\n",bno,bname,author,publisher,price);
}
}
fclose(f);
}
fprintf():
fprintf() is used to write the data into the stream.Stream can be standard output device or
it can be a file.
The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted
output to a stream.
Syntax:
Parameters:
stream − This is the pointer to a FILE object that identifies the stream. Stream also can
be terminal that is standard output device in such case the first parameter is stdout.
format − This is the C string that contains the text to be written to the stream. It can
optionally contain embedded format tags that are replaced by the values specified in
subsequent additional arguments and formatted as requested. Format tags prototype is %
[flags][width][.precision][length]specifier, which is explained below −
specifier Output
c Character
d or i Signed decimal integer
e Scientific notation (mantissa/exponent) using e character
E Scientific notation (mantissa/exponent) using E character
f Decimal floating point
g Uses the shorter of %e or %f
G Uses the shorter of %E or %f
o Signed octal
s String of characters
u Unsigned decimal integer
x Unsigned hexadecimal integer
X Unsigned hexadecimal integer (capital letters)
p Pointer address
n Nothing printed
% Character
Return Value
If successful, the total number of characters written is returned otherwise, a negative number is
returned.
Example:
#include<stdio.h>
void main()
FILE *fp;
int n,i,rno;
float tmarks;
char name[10];
fp=fopen(“a.txt”,”w”);
fprinf(stdout,”%s”,”how many record you want to enter\n”);
fscanf(stdin,”%d“,&n);
for(i=1;i<=n;i++)
fprintf(fp,”%s%d%f”,name,&rno,&tmarks);
fclose(fp);
printf(“name\troll num\tmatks”);
fp=fopen(“a.txt”,”r”);
while((fscanf(fp,”%s%d%f”,name,&rno,&tmarks))!=EOF)
fprintf(fp,”%s%d%f”,name,rno,tmarks);
fclose(fp);
10. With an example explain how to handle errors during I/O operations.
When we are performing I/O operations on the file error may occur. Some of the error
includes:
iv) Trying to perform an operation on a file when the file is opened for another
type of operation.
v) Opening a file with an invalid filename.
There are two functions available to check the errors they are:
ferror() and feof() which helps us to detect errors during I/O operation.
i)feof():
feof() is used to check whether the file pointer is reached end of the file.
syntax:
Parameter:
This function takes a single parameter which is the pointer to the FILE structure of the
stream to check pointer is reached end of the file or not.
Return value:
This function returns a non-zero value when end of file indicator associated with the
stream is set, else zero is returned.
ii)ferror():
Syntax:
Parameter:
It takes a single argument that is the file pointer which is pointing to a FILE object that
identifies the stream.
Return value:
Returns 0 if the file pointer fp successfully reads all character present in a file ,non-zero
integer value when an error has been detected during processing.
fp=fopen(“a.txt”,”r”);
if(ferror(fp)!=0)
printf(“error\n”);
Also the error can be detected by comparing file pointer with NULL .File pointer fp
contains NULL if the file cannot be opened for some reason otherwise it is pointing to
the first character in the file.
if(fp==NULL)
printf(“cannot open\n”);
#include<stdio.h>
void main()
char *filename;
FILE *fp1,*fp2;
int i,number;
fp1=fopen(“test.txt,”w”);
for(i=10;i<=100;i+=10)
putc(i,fp1);
fclose(fp1);
printf(”Input filename\n”);
open_file:
scanf(“%s”,filename);
if((fp2=fopen(filename,”r”))==NULL)
goto open_file;
}
else
for(i=1;i<=20;i++)
number=getc(fp2);
if(feof(fp2))
break;
else
printf9”%d\n”,number);
fclose(fp2);
OUTPUT:
TEST.txt
TEST:
10
20
30
40
50
60
70
80
90
100
File contents are read or written sequentially. There are situation in which the user want
to read only some part of the file. In such occasion random access to the file is important.
This can be achieved with the help of the function’s fseek, ftell and rewind available in
the library <stdio.h>.
fseek()
The fseek() function is used to set the file position indicator associated with stream
according to the values of offset and position. The purpose of it is to support the random
access I/O operations. The offset is the number of bytes from the position to seek to. The
values for position must be one of the following macros defined in <stdio.h>
Syntax:
Parameters:
fseek() function takes 3 parameters: first one is file pointer second parameter is offset
and the thirds parameter is the position.
Return Value:
Statement Meaning
Example:
#include<stdio.h>
void main()
FILE *fp;
fp=fopen(“a.txt”,”w”);
fprintf(fp,”%s”,”data structure”);
fseek(fp,4,0);
frintf(fp,”%s”, java”);
fclose(fp);
In the above example fseek position is set from the beginning the value of the offset is m
which is 4. That means the file pointer fp will move to (m+1)th character that is to the 5 th
chatacter .From the fifth character the string java is written.New content of the file is
datajavaucture.
ftell():
This function is used to get the current pointer position in the file. Position value starts
from 0….n in some OS like Linux and in some OS it starts with 1….n.
Syntax:
Parameters
stream − This is the pointer to a FILE object that identifies the stream.
Return Value
This function returns the current value of the position indicator. If an error occurs, -1L is
returned, and the global variable errno is set to a positive value.
Example
#include <stdio.h>
int main () {
FILE *fp;
int len;
fp = fopen("file.txt", "r");
if( fp == NULL ) {
perror ("Error opening file");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
return(0);
}
OUTPUT:
Data structure
Total size of file.txt =15.
/*Program to enter A-Z from the console and display every fifth character and its
position then printing all the character in reverse order.*/
#include<stdio.h>
Void main()
{
FILE *fp;
long n;
char c;
fo=fopen(“random”,”w”0;
while((c=getchar())!=eof)
putc(c,fp);
printf(“no of characters in is %ld\n”,ftell(fp));
fclose(fp);
fp=fopen(“random”,”r”);
n=0L
while(feof(fp)==0)
{
fseek(fp,n,0);
printf(“position of %c is %ld\n”,getc(fp),ftell(fp));
n=n+5L;
}
putchar(‘\n’);
fseek(fp,-1L,2)//move the fp from eof to z one step backward*/
do
{
putchar(getc(fp));
}while(!seek(fp,-2L,1));/* when the z is read fp will positing to next character from
current position 2 steps we need to come backward to read y and the other characters*/
fclose(fp);
}
OUTPUT:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
No of character eneterde is =26
Position of A is 0
Position of F is 5
Position of K is 10
Position of P is 15
Position ofUis 20
Position of Z is 25
Position of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA.
iii)rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax:
rewind( fptr);
Where fptr is a file pointer.
Parameter:
This function takes a single parameter which is file pointer.
Return value:
On success it reruns zero and on failure returns non-zero value.
Example:
#include<stdio.h>
void main()
FILE *fp;
char ch;
fp=fopen(“a.txt”,”r”);
while((ch=getc(fp))!=EOF)
printf(“%c”,ch);
}
rewind(fp);
ch=getc(fp);
fclose(fp);
OUTPUT:
data structure
Character read is :d
/*Write a program to append additional items to the file Inventory and print its
contents*/
#include<stdio.h>
struct record
char name[10];
int number;
float price;
int quantity;
};
main()
char filename[10];
int response;
FILE *fp;
long n;
scanf(“%s”,filename);
fp=fopen(filename,”a+”);
do
append(&item,fp);
printf(“item %s is appended\n”,item.name);
scanf(“%d”,&response);
}while(response==1);
n=ftell(fp);
fp=fopen(filename,”r”);
while(ftell(fp)<n)
fscanf(fp,”%s%d%f%d”,item.name,&item.number,&item.price,&item.quantity);
fprintf(stdout,,”%s%d%f%d”,item.name,item.number,item.price,item.quantity);
fclose(fp);
scanf(“%s”,product->name);
printf(“enter item number\n”);
scanf(“%d”,&product->number);
scanf(“%f”,&product->price);
printf(“enter quantity\n”);
scanf(“%d”,&product->quantity);
fprintf(ptr,”%s%d%f%d”,product->name,product->number,product->price,product->quantity);
OUTPUT:
Item number: 33
Item price: 20
Quantity:34
Pen 12 5 28
Soap 33 20 34
Write a C program to reverse the last n character in a file. The file name and the value
of n are specified on the command line. Incorporate validation of arguments, that is
the program should check that the number of arguments passed and the value of n
that are meaningful.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main(int argc,char *argv[])
FILE *f;
char s[10],c;
int i,j,n;
if(argc!=3)
exit(0);
f=fopen(argv[1],”r”);
if(f==null)
exit(0);
i=0;
while(1)
if((c=getc(f))!=eof)
j=i+1;
else
break;
fclose(f);
f=fopen(argv[1],”w”);
exit(0);
j=strlen(s);
for(i=1;i<=n;i++)
j--;
putc(s[j],f);
fclose(f);
>a m.txt 4
Database
Dataesab
Write a C program to reverse the first n character in a file. The file name and the
value of n are specified on the command line. Incorporate validation of arguments,
that is the program should check that the number of arguments passed and the value
of n that are meaningful.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
FILE *f;
char s[10],c;
int i,j,n;
if(argc!=3)
exit(0);
f=fopen(argv[1],”r”);
if(f==null)
exit(0);
i=0;
while(1)
if((c=getc(f))!=eof)
{
j=i+1;
else
break;
fclose(f);
f=fopen(argv[1],”w”);
exit(0);
for(i=n-1;i>=0;i--)
putc(s[i],f);
fclose(f);
OUTPUT:
>a m.txt 4
Database
ataDbase
12. What is command line argument? What is the use of argc and argv[] ?Write a
program to copy the content of one file to another using command line argument.
Command line arguments are given along with the command or after the program name
in OS like Linux or DOS are passed into the program from OS.
We know that every C program should have one main() function and that it marks the
beginning of the program .Main program also takes arguments. It takes two arguments:
first one is the argc which is the argument count is an integer value used to store the
number of arguments that you are passed in command line including program name or
name of the command .
Second parameter to the main() is argv[] which is the argument vector which stores the
list of arguments that you are passing in the command line including the name of the
command or program name.
The declaration of the main() can be given as :int main(int argc,char *argv[])
argv[0] contains the name of the program or the name of the command, argv[1] contains
the second argument so on..
Example:
/* program to copy one file to another file using command line arguments*/
#include<stdio.h>
FILE *fr,*fw;
int ch;
if(argc!=3)
return 1;
}
fr=fopen(argv[1],"r");
if(fr==NULL)
return 1;
fw=fopen(argv[2],"w");
if(fw==NULL)
fclose(fr);
return 1;
while((ch=fgetc(fr))!=EOF)
fputc(ch,fw);
fclose(fr);
fclose(fw);
return 0;
OUTPUT
c:\TDM-GCC-32>gcc filearg.c
data structure
w.txt
data structure
Write a program that will receive a filename and a line of text as command line
arguments and write the text to the file.
#include<stdio.h>
FILE *fp;
int i;
char word[10];
fp=fopen(argv[1],”w”);
for(i=1;i<argc;i++)
fprintf(fp,”%s”,argv[i]);
fclose(fp);
fp=fopen(argv[1],”r”);
for(i=2;i<argc;i++)
fscanf(fp,”%s”,word);
fprintf(stdout,”%s\n”,word);
fclose(fp);
}
data
structure
programming
using
Write a program that reads a file containing integers and appends at its end sum of all
the integers.
#include<stdio.h>
#include<stdlib.h>
void main()
int n,sum;
FILE *fp;
fp=fopen(“r.txt”,”r”);
if(fp==null)
exit(0);
while((n=getw(fp))!=EOF)
sum=sum+n;
fclose(fp);
fp=fopen(“r.txt”,”a”);
putw(n,fp);
fclose(fp);
OUTPUT:
r.txt:
Sum=10
Question bank
5 marks questions
1. What is file ? Explain how to open and close a file.
10 marks questions
1. Differentiate between following functions: