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
- How to Use Canva Pro For FREE
- How To Use Adobe Lightroom, Photoshop, etc for FREE on MAC
- How To Use Final Cut Pro X for FREE Forever
- How to use Parallels for FREE FOREVER on Macbook (M1+Intel)
- How To Use Microsoft Office Apps For FREE (even offline)
- How To Read Wall Street Journal, NY Times, etc For FREE