-->

Header Ads

C Program to Perform Read and Write Operation on File(file handling).

Here i am discussing how to write on any file and read them by using c language.my objective is to create a file and write something on it and after that read  file content and print it on console.

                                  its simple as you all  know about basic file handling in c. I am using fopen() function to create new file "file1.txt" in write mode. fopen() function takes two argument first one is name of file which u want to create or edit (if file already exists), second is mode of file (ex: read-r,write-w,append-a etc.).Here i want to write on file so that i use write mode as 'w'. f1 and f2 is file pointer which points file 'file1.txt'. gets() function is use to take input string from console. whatever user enters on console it stored in array 'ch[ ]'. fprintf() function write the content of array 'ch[ ]' on file 'file1.txt' which pointed by f1 pointer. at the end of writing content on file1.txt, close file so that content will be store on file.                                                        
         Now come to the next part of program that is to print content of file1.txt on console. open file in read mode and scan character by character and print character on screen untill end of file.


C Program:

#include<stdio.h>

#include<conio.h>

void main()

{

clrscr();

FILE *f1,*f2;

char ch[100],data[100];

     f1=fopen("file1.txt","w");

 if(f1==NULL)

 printf("\nERROR");

     printf("enter data");

     gets(ch);



     fprintf(f1,"%s",ch);

     fclose(f1);



     f2=fopen("file1.txt","r");

     printf("\ncontent on file are as :");



     while(fgets(data,99,f1)!=NULL)

 {

 printf("%s",data);

 }

 fclose(f2);

getch();


}

Output:


No comments

Powered by Blogger.