I’m writing some code so that at each iteration of a for loop it runs a functions which writes data into a file, like this:
int main()
{
int i;
/* Write data to file 100 times */
for(i = 0; i < 100; i++) writedata();
return 0;
}
void writedata()
{
/* Create file for displaying output */
FILE *data;
data = fopen("output.dat", "a");
/* do other stuff */
...
}
How do I get it so that when I run the program it will delete the file contents at the beginning of the program, but after that it will append data to the file? I know that using the "w" identifier in fopen() will open a new file that’s empty, but I want to be able to ‘append’ data to the file each time it goes through the writedata() function, hence the use of the "a" identifier.
This is how you should really do it. This way you only need to open the file once, and it will be truncated when you do. Note that you’ll have to change your function prototype as well (wherever it is).