Examples
We are in a position to write some programs based on files now.
Example
1: Write a C program that accepts one line of text from the keyboard one
character at a time and writes it into a disk file. Then read that file, test1.dat, one character at
a time and print the result on the screen.
Solution 1:
The following is the program:
#include
#include
void main( )
{
FILE *fp;
char ch;
clrscr( );
fp = fopen(“test1.dat”, “w”);
if (fp = = NULL)
{
printf(“\n Cannot open file”);
exit(1);
}
printf(“\n Type a line of text and press Enter key \n”);
while (( ch = getche( ) ) != ‘\r’)
fputc(ch, fp);
fclose (fp);
}
Do'stlaringiz bilan baham: