OUTPUT (after running):
Type a line of text and press Enter key
I am Dr. Rajiv Chopra
/* now reading data from the file */
#include
#include
void main( )
{
FILE *fp;
char ch;
clrscr( );
if ((fp = fopen(“test1.dat”, “r”)) = =NULL)
{
printf(“\n Cannot open file”);
exit(1);
}
while ((ch = fgetc (fp)) != EOF)
putchar(ch);
fclose(fp);
getch( );
}
OUTPUT (after running):
I am Dr. Rajiv Chopra
NOTE
If you have to read and write strings rather than characters (as shown above), we use
the fputs( ) and puts( ) functions.
Example
2: Write a C program to
(a)
Write integer data into a file.
(b)
Read the same data from the file.
Solution 2(a):
#include
#include
void main( )
{
FILE *fp;
char ch;
clrscr( );
if ((fp = fopen(“test1.dat”, “r”)) = =NULL)
{
printf(“\n Cannot open file”);
exit(1);
}
while (ch = =’y’)
{
printf(“\n Enter any integer:”);
scanf(“%d”, &n);
putw (n, fp);
printf(“\n Want to eneter another number (y/n)?”);
ch = tolower (getche( ));
}
fclose (fp);
}
Do'stlaringiz bilan baham: |