WAP Using C to Write and Read in a File

By Suraj Chaudhary

In this article, I will show you exactly how to write a file-handling program using C language to write and read in a .txt file.

//Wap to write emp id, name and address on "emp.dat" file and read it.
#include
#include
#include 
int main ()
{
//Create a file pointer
  FILE *fp;
  int id;
  char name[20];
  char add[20];
  //Open a file
  fp = fopen ("emp.dat", "w");
  printf ("Enter name: ");
  scanf ("%s", name);
  printf ("Enter address: ");
  scanf ("%s", add);
  printf ("Enter id: ");
  scanf ("%d", &id);
  //write data into file
  fprintf (fp, "%s\n%s\n%d\n", name, add, id);
  //close the file
  fclose (fp);
  fp = fopen ("emp.dat", "r");
  //check if the file exists or not
  if (fp == NULL)
    {
      printf ("Unable to find");
      exit (1);

    }
    //if file exists runs the code below if it doesn't exist then code stops.
  else
    {
//While loop to stop the code once it reaches the End of the file.
      while (fscanf (fp, "%s\n%s\n%d\n", name, add, &id) != EOF)
	{
	  printf ("Enter name: ");
	  scanf ("%s", name);
	  printf ("Enter address: ");
	  scanf ("%s", add);
	  printf ("Enter id: ");
	  scanf ("%d", &id);
	}

    }
    //close again
  fclose (fp);
  return 0;
}

If you have any confusion, feel free to drop a comment down below. You can also read the below-given articles.

Also Read
  1. How to Use Canva Pro For FREE
  2. How To Use Adobe Lightroom, Photoshop, etc for FREE on MAC
  3. How To Use Final Cut Pro X for FREE Forever
  4. How to use Parallels for FREE FOREVER on Macbook (M1+Intel)
  5. How To Use Microsoft Office Apps For FREE (even offline)
  6. How To Read Wall Street Journal, NY Times, etc For FREE

Suraj Chaudhary is a writer, developer, founder, and a constant learner. He shares lessons and resource to living a fuller life every week. On this blog, he shares helpful guides and helpful articles that help his 70,000+ monthly readers find answers, solve problems, and meet their curious needs.

Leave a Comment

Slide to prove you're not a bot/spammer *