Skip to main content

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

  1. Open a file in write mode.
  2. Check if the file created successfully.
  3. Prompt user to enter age.
  4. Loop until user enter Enter or G.
  5. Write in file.
  6. Close file.
  7. Open file again in read mode.
  8. Print the contents of file.
  9. Close opened file.
  10. 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.