Writing data to text file in 'C'

Home Forums Programming Writing data to text file in 'C'

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #930
    Basavaraj
    Member
    #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.txt

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

    3. Closing the file.
    fclose(p) closes file Hello.txt.

    #963
    Satish
    Keymaster
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.