17.
Store and read data from
a text file.
# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[100];
clrscr();
printf( "Opening the file test.txt in write mode\n" ) ;
fp = fopen("test.txt", "w") ;
if(fp == NULL )
{
printf( "\nCould not open file test.txt" ) ;
return 1;
}
printf( "\nEnter some text from keyboard to write in the file
test.txt\n" ) ;
while (strlen(gets(data))>0)
{
/*
writing in the file*/
fputs(data,
fp) ;
fputs("\n",
fp) ;
}
/* closing the file*/
printf("\nClosing the file test.txt") ;
fclose(fp) ;
printf( "\nOpening the file test.c
in read mode" ) ;
fp = fopen( "test.txt",
"r" ) ;
if ( fp == NULL )
{
printf( "\nCould not open file
test.txt" ) ;
return 1;
}
printf( "\nReading the file
test.txt\n" ) ;
while( fgets ( data, 100, fp ) != NULL )
printf( "%s" , data ) ;
printf("\nClosing the file
test.txt\n") ;
fclose(fp) ;
return 0;
}
No comments:
Post a Comment