Home › Forums › Programming › Writing data to text file in 'C'
- This topic has 1 reply, 2 voices, and was last updated 12 years, 11 months ago by Satish.
- AuthorPosts
- December 29, 2011 at 2:01 pm#930BasavarajMember
#include<stdio.h> void main() { FILE *p; char ch; p=fopen("d:\\Hello.txt","w"); clrscr(); printf("\n\nEnter the text\n"); while( (ch=getche() ) !='\r' ) { fputc( ch,p); } fclose(p); }
This example illustrates writing data ( in this example text is written ) to a text file, files are stored in secondary storage device such as Hard disk, in c it is possible to create a file and read/write data to it,for this purpose we need a pointer of type FILE.
writing data to a file in ‘C’ includes following steps.1. open a file using the function fopen() it takes 2 arguments first represents path and name of the file, sencond argumnets represents file opening mode.
in this example a file called Hello.txt is opened in d drive,”w” indicated write mode,fopen() function returns reference to the file which is stored in the pointer p,this pointer is further used for referring file Hello.txt2. Writing data to file.
while( (ch=getche() ) !=’\r’ ) this line reads text typed by the user character by character and till user hits enter key.
the line fputc( ch,p ) writes character present in ch to the file Hello.txt3. Closing the file.
fclose(p) closes file Hello.txt.January 2, 2012 at 7:17 am#963SatishKeymaster - AuthorPosts
- You must be logged in to reply to this topic.