Tuesday, November 14, 2017

Use of fprintf and fscanf

File management: Program to demonstrate use of fprintf() and fscanf() function. This program will read a word from keyboard and write it into a data.txt file. After closing a file, program will again open it and get a word from file and display on screen.



#include <stdio.h>
#include <stdlib.h>
int main()
{
  FILE *fp;
  char str[80], str1[80];

  fp = fopen("data.txt","w");

  if(fp == NULL)
  {
printf("Cannot open file.\n");
exit(1);
  }
  printf("Enter string to be written in a file: ");
  fscanf(stdin, "%s", str); /*Read from keyboard */

  fprintf(fp, "%s", str); /*Write str to file */
  fclose(fp);

  fp = fopen("data.txt","r");

  if(fp == NULL) {
printf("Cannot open file.\n");
exit(1);
  }
  fscanf(fp, "%s", str1); /* read a word from file and copy into str1 */
  fprintf(stdout, "%s", str1); /* print str1 on screen */
  return 0;
}

Output of program

Enter string to be written in a file: Hello
Hello

No comments:

Post a Comment