While programming with the struct data type, I have a .txt that I wish to write to and I am unable to do so. Below I showcase my code, the problem is the contents of my file become overridden whereas I wish to simply add onto it.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// a struct to read and write
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *outfile;
// open file for writing
outfile = fopen ("person.txt", "w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opened file\n");
exit (1);
}
struct person input1 = {1, "rohan", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};
// write struct to file
//fwrite (&input1, sizeof(struct person), 1, outfile);
//fwrite (&input2, sizeof(struct person), 1, outfile);
//Why does the above erase the contents already in my file
//I want to keep them and to add the above lines to the file
if(&fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
return 0;
}