C Programming Articles

WRITING TO AND READING FROM A FILE

Write a program to read data from the keyboard, write it to a file called INPUT, again read the same data from the INPUT file, and display it on the screen.

Code for WRITING TO AND READING FROM A FILE in C Programming

#include <stdio.h>
main()
{
FILE *f1;
char c;
printf("Data Input\n\n");
/* Open the file INPUT */
f1 = fopen("INPUT", "w");
/* Get a character from keyboard */while((c=getchar()) != EOF)
/* Write a character to INPUT */
putc(c,f1);
/* Close the file INPUT */
fclose(f1);
printf("\nData Output\n\n");
/* Reopen the file INPUT */
f1 = fopen("INPUT","r");
/* Read a character from INPUT*/while((c=getc(f1)) != EOF)
/* Display a character on screen */
printf("%c",c);
/* Close the file INPUT */
fclose(f1);
}
Output
Data Input
This is a program to test the file handling
features on this system^Z
Data Output
This is a program to test the file handling
features on this system