You are on page 1of 38

UNIT-II

FILES (17 marks)


INTRODUCTION
Real world application involves huge amount of the data is to be processed. So entering
data from input device like keyboard is a tedious job. The console oriented operations
has two major problems:
1. It is a time consuming process to handle large amount of data through terminals.
2. The entire data is lost when either the program is terminated or the computer is turned
off.
A more flexible approach is necessary to handle large amount of data easily .This method
employs the concept of files to store data.
1. What is file explain how to open and close a file.
DEFINITION OF FILE
A file is a place on the disk where a group of related data is stored.
C supports a number of functions that have the ability to perform basic file operations,
which include:
i) Naming a file
ii) Opening a file
iii) Reading data from a file
iv) Writing data to a file
v) Closing a file
There are two distinct ways to perform file operations in C.The first one is using low-
level I/O and Unix system calls(functions) .
The second method is referred to as high-level I/O operation and uses functions in C’s
standard I/O library.
DEFINING AND OPENING A FILE:

OPENING A FILE:

fopen() is used to open a file.


If we want to store the data in a file in the secondary memory, we must specify certain things about the
file to the OS. They include high level I/O functions available in C’s library. Some of them are:

Function name Operation


fopen() Creates a new file for use.
Opens an existing file for use.
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 file
getw() Reads an integer from a file
putw() Writes an integer to a 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

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.

Mode can be one of the following:

r opens the file for reading only.

w opens the file for writing only

a open the file for appending data to it.

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.

Consider the following statements:

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.

Many recent compilers include additional modes of operation.

They include:

r+ The existing file is opened to the beginning for both reading and writing.

w+ Same as w except both for reading and writing

a+ Same as a except both for reading and writing.

We can open and use a number of files at a time. This number however depends on
the system we use.

Example for fopen():


#include<stdio.h>

#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:

int fclose(FILE *stream);

Parameter:

It takes one parameter that is the file pointer .


stream: This is the pointer to a FILE object that specifies the stream to be closed.

Return value:

This method returns zero if the stream is successfully closed. On failure, EOF is
returned.

Example: FILE fp;

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().

2. Explain input/output functions of file.


3. With an example explain how to read a single character from a file.

4. With an example explain how write a single character to a file.

5. With an example explain how read integer value from a file.

6. With an example explain how to write an integer value to a file.

7. With an example explain how to read stream or set of data from a file.

8. With an example explain how write a set of data or stream to a file.

INPUT/OUTPUT OPERATIONS ON FILES:


Reading and writing a single character:

getc() and putc():

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)

printf(“can not opening file\n”);

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:

putc(int character variable,filepointer);

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");

printf("Enter the character one by one\n");

while((ch=getchar())!='\n')

putc(ch,fp);

fclose(fp);

OUTPUT:

Enter the character one by one

Programming

Reading and writing integer value from and to a file:

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 :

int getw(file pointer);


Parameter:

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");

while((num = getw(fp))!=EOF) //Statement 2


printf("\n%d",num);

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 is used to write integers to the file.

Syntax of putw() function

putw(int number, FILE *fp);

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);

printf("\nDo you want to another number : ");


ch = getche();

}while(ch=='y'||ch=='Y');

printf("\nData written successfully...");

fclose(fp);
}
Output :

Enter any number : 78


Do you want to another number : y
Enter any number : 45
Do you want to another number : y
Enter any number : 63
Do you want to another number : n
Data written successfully...

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);

printf(“out put data\n”);

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.

Reading set of data and writing set of data to a file:


9. Explain fscanf() and fprintf() in file.

fprintf() and fscanf():

i)fscanf():

fscanf() is used to read formatted input from a stream.

Syntax:

int fscanf(stream,control string,address list);

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:

Following is the declaration for fprintf() function.

int fprintf(FILE *stream, const char *format, ...)

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);

fprintf(stdout,”%s”,”enter name roll num total marks\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.

ERROR HANDLING DURING I/O OPERATIONS:

When we are performing I/O operations on the file error may occur. Some of the error
includes:

i) Trying to read beyond the end of the file

ii) Device overflow

iii) Trying to use a file that has been opened

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.

vi) Attempting to write to a file which doesn’t have write permission.

Whenever the error occurs program may terminate abnormally.

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:

int foef(file pointer);

file pointer is a pointer to the file of type FILE.

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():

ferror() function reports the status of the file indicated.

Syntax:

int ferror(file pointer);

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”);

/* program to illustrate error handling in file operations*/

#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)

printf(“Cannot open the file:\n”);

printf(“Type the file name again\n”);

goto open_file;
}

else

for(i=1;i<=20;i++)

number=getc(fp2);

if(feof(fp2))

printf(“\n ran out of data\n”0;

break;

else

printf9”%d\n”,number);

fclose(fp2);

OUTPUT:

Input file name:

TEST.txt

Cannot open file

Type filename again

TEST:

10
20

30

40

50

60

70

80

90

100

Ran out of data.

11. Explain fseek() and ftell() functions.

RANDOM ACCESS TO FILES:

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:

fseek( file pointer, offset, position);

Parameters:

fseek() function takes 3 parameters: first one is file pointer second parameter is offset
and the thirds parameter is the position.

file pointer ---- It is the pointer which points to the file.


offset ---- It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward ( if positive) from the current position. This is attached
with L because this is a long integer.
position:
This sets the pointer position in the file.

Value pointer position


0 or SEEK_SET Beginning of file.
1 or SEEK_CUR Current position
2 or SEEK_END End of file

Return Value:

This function returns zero if successful, or else it returns a non-zero value.

Operations of fseek function

Statement Meaning

fseek(fp,0L,0) Go to the beginning

fseek(fp,0L,1) Stay at the current position

fseek(fp,0L,2) Go to the end of the file

fseek(fp,m,0) Move to (m+1)th character or byte in the file

fseek(fp,m,1) Go forward by m character

fseek(fp,-m,1) Go backward by m bytes from the current position

fseek(fp,-m,2) Go backward by m bytes from the end

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:

Following is the declaration for ftell() function.

long int ftell(FILE *stream)

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

The following example shows the usage of ftell() function.

#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);

printf("Total size of file.txt = %d bytes\n", len);

return(0);
}
OUTPUT:
Data structure
Total size of file.txt =15.

program to illustrate fseek() and ftell()

/*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”);

printf(“content of the file is\n”);

while((ch=getc(fp))!=EOF)

printf(“%c”,ch);

}
rewind(fp);

ch=getc(fp);

printf(“character read is %c”,ch);

fclose(fp);

OUTPUT:

Content of the file is :

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()

struct record item;

char filename[10];

int response;

FILE *fp;
long n;

void append(struct rtecord*,FILE*);

printf(“Enter the file name\n”);

scanf(“%s”,filename);

fp=fopen(filename,”a+”);

do

append(&item,fp);

printf(“item %s is appended\n”,item.name);

printf(“do you want to add another item:-1-yes 0-no\n”);

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);

void append(struct record *product,FILE *ptr)

printf(“enter item name\n”);

scanf(“%s”,product->name);
printf(“enter item number\n”);

scanf(“%d”,&product->number);

printf(“enter item price\n”);

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:

Type filename: Inventory

Item name: soap

Item number: 33

Item price: 20

Quantity:34

Item soap is appended

Do you want to add any more items? 0

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)

printf(“invalid number of arguments\n”);

exit(0);

n=atoi(argv[2]);//read value of n will be store as character convert ascii to integer

f=fopen(argv[1],”r”);

if(f==null)

printf(“can not find this file\n”);

exit(0);

i=0;

while(1)

if((c=getc(f))!=eof)

j=i+1;

else
break;

fclose(f);

f=fopen(argv[1],”w”);

if(n<0||n>strlen(s))/*if the value of n is less thatn zero or it is trying to exceed string


length*/

printf(“incorrect value of n\n”);

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>

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

FILE *f;

char s[10],c;

int i,j,n;

if(argc!=3)

printf(“invalid number of arguments\n”);

exit(0);

n=atoi(argv[2]);//read value of n will be store as character convert ascii to integer

f=fopen(argv[1],”r”);

if(f==null)

printf(“can not find this file\n”);

exit(0);

i=0;

while(1)

if((c=getc(f))!=eof)

{
j=i+1;

else

break;

fclose(f);

f=fopen(argv[1],”w”);

if(n<0||n>strlen(s))/*if the value of n is less than zero or it is trying to exceed string


length*/

printf(“incorrect value of n\n”);

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:


C facilitates its programmer to pass arguments in command line.

Command line argument is a parameter supplied to a program when the program is


invoked.

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..

In C every element in the argv[] can be used as string.

Example:

/* program to copy one file to another file using command line arguments*/

#include<stdio.h>

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

FILE *fr,*fw;

int ch;

if(argc!=3)

printf("Invalid numbers of arguments.");

return 1;
}

fr=fopen(argv[1],"r");

if(fr==NULL)

printf("Can't find the source file.");

return 1;

fw=fopen(argv[2],"w");

if(fw==NULL)

printf("Can't open target file.");

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

c:\TDM-GCC-32>a r.txt w.txt


r.txt

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>

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

FILE *fp;

int i;

char word[10];

fp=fopen(argv[1],”w”);

printf(“the number of arguments in the command line is :%d”,argc);

for(i=1;i<argc;i++)

fprintf(fp,”%s”,argv[i]);

fclose(fp);

/* writing the content of the file to the screen*/

fprintf(stdout,”content of the file is:%s”,arv[1]);

fp=fopen(argv[1],”r”);

for(i=2;i<argc;i++)

fscanf(fp,”%s”,word);

fprintf(stdout,”%s\n”,word);

fclose(fp);
}

>a m.txt data structure programming using c

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)

printf(“can not read\n”);

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.

2. Distinguish between the following functions:

a) Getc and getchar

b) Printf and fprintf

3. With an example, explain how to handle errors during I/O operations.

4. Explain fseek() and ftell() functions.

10 marks questions
1. Differentiate between following functions:

i)feof and ferror

ii)printf and fprintf

iii) getc and getw


2.Write a program to copy the content of one file to another.Use command line
arguments to specify the file names.

3. List and explain Input/Output functions of file.

4. Explain different file accessing modes.

You might also like