Thursday, July 21, 2011

File Operations in C:Source Code to Write Text to a File ,Copy it to a new Location


File Operations in C are accomplished by the use of pointers.Pointers are use to point to a particular memory location.File are read and written by using file pointers.The Keyword FILE is used to declare a file pointer.

eg:FILE *fp
      Here fp is a file pointer.* before a variable name indicates that the variable is a pointer.

The Program given below demonstrates how to write strings read from keyboard to a file and how to copy the file into a new location.It mainly uses two file pointers fi and fo.

fi- Input file pointer
fo- Output file pointer

fopen is the function used to open a file and assign the address of the first character to a pointer

eg: fo=fopen("c:\myfile.txt","wb");

Here 'myfile' is opened and pointer fo is used to point to that file.This file is opened in the 'write binary' mode.There are different modes of opening files in C. 'write binary' means binary data can be written to the file.The important modes of opening files in C are 

r-read Only Mode
w-Write Only Mode
a-Appending Mode for appending data to an existing file

There are many more modes of opening files, these will be discussed in detail in another post.
 #include<stdio.h>  
 void main()  
 {  
 FILE *fi,*fo;  
 char c;  
 char fin[125],fout[125],indata[500];  
 clrscr();  
 puts("             File Input&Copy             " );  
 puts("Input Data \n");  
 gets(indata);  
 puts("\nSave File as: ");  
 gets(fout);  
 fo=fopen(fout,"w");  
 fi=fopen(fout,"r");  
 fprintf(fo,indata);  
 puts("\nSave copy as: ");  
 gets(fout);  
 fo=fopen(fout,"w");  
 while(1)  
 {  
 c=getc(fi);  
 if (c==EOF)  
 break;  
 putc(c,fo);  
 }  
 puts("File copied successfully");  
 puts("\n");  
 printf("Reading from file:%s \n \n ",fout);  
 fprintf(fo,indata);  
 puts(indata);  
 getch();  
 }  

0 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.