Practical-25
Write a c program to read data from keyboard write it to a file called input and Display data of input file on the screen.
Introduction
This program reads data from keyboard and writes it to a file called input. Then it displays the data of input file on the screen.
Algorithm
- Open a file in write mode.
- Check if the file created successfully.
- Prompt user to enter age.
- Loop until user enter Enter or G.
- Write in file.
- Close file.
- Open file again in read mode.
- Print the contents of file.
- Close opened file.
- Exit.
Code
Practical-25.c
#include <stdio.h>
int main()
{
FILE *input; // creating file pointer
// open file in write mode
input = fopen("input", "w");
// check if the file created successfully
if (input == NULL)
{
printf("Error opening file!\n");
return 0;
}
char c; // creating character variable
// prompting user to enter age
printf("Please enter your age: ");
// looping until user enter Enter or G
while ((c = getchar()) != '\n' && c != EOF)
{
putc(c, input); // writing in file
}
// closing file
fclose(input);
// open file again in read mode
input = fopen("input", "r");
// print the contents of file
printf("\nYour Details:\n");
while ((c = fgetc(input)) != EOF)
{
printf("%c", c);
}
printf("\n");
// close opened file
fclose(input);
return 0;
}
Output
Please enter your age: 20
Your Details:
20
Explanation
This program reads data from keyboard and writes it to a file called input. Then it displays the data of input file on the screen.