Saturday 18 December 2010

Program which copies one file to another

Description:


In this program we have to use the file functions to perform the copy operation from one file to another file.

Program:

#include <stdio.h> #include <conio.h> #include <process.h>

void main(int argc, char *argv[])
{
FILE *fs,*ft; char ch; clrscr(); if(argc!=3)
{
puts("Invalid number of arguments."); exit(0);
}
fs = fopen(argv[1],"r"); if(fs==NULL)

{
puts("Source file cannot be opened."); exit(0);
}
ft = fopen(argv[2],"w");
if (ft==NULL) // check the condition if the file pointer is NULL or not

{
puts("Target file cannot be opened."); fclose(fs);
exit(0);
}
while(1)
{
ch=fgetc(fs);
if (ch==EOF) // check the condition if the file is end or not break;
else fputc(ch,ft);

}
fclose(fs);
fclose(ft);
getch();
}

Output:


source.c
this is source text
ouput.c

Command line arguments source.c    ouput.c
Source.c
this is source text ouput.c
this is source text

Command line arguments source.c
Invalid number of arguments.

Conclusion: the program is error free


VIVA QUESTIONS:

1) What is file ?
Ans: The collection of alphabets is called file

2) What are the various operations performed on the file ? Ans: fopen(), fread(), fwrite(), fclose() etc..,

3) What is the use of file pointer ?
Ans: The file pointer must be used in subsequent operations on the file





Files
pointers

No comments:

Post a Comment