How to clear file contents with c?

I am writing code so that at each iteration of the for loop, functions are executed that write data to a file, for example:

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 can I get it so that when I start the program it will delete the contents of the file at the beginning of the program, but after that it will add data to the file? I know that using the identifier "w" in fopen () will open a new empty file, but I want to be able to "add" data to the file every time it performs the function "writedata ()", therefore, using the identifier "a".

+3
source share
6 answers

. , , , . , ( ).

int main()
{
    int i;

    FILE *data;
    data = fopen("output.dat", "w");
    if(!data) {
         perror("Error opening file");
         return 1;
    }

    /* Write data to file 100 times */
    for(i = 0; i < 100; i++)    writedata(data);

    fclose(data);

    return 0;
}

void writedata(FILE *data)
{

    /* do other stuff */
    ...
}
+6

, , , ftruncate() POSIX - , .

+4

?

writedata w+ writedata, /* do other stuff */ ?

+3

? , .

#include<stdio.h> 
static int t = 0;    
void writedata()
{
   FILE* data;
   if(t == 0) {
      data = fopen("output.dat", "w");
      t++;
   } else {
      data = fopen("output.dat", "a");
   }
} 

int main()
{
    int i;
    for(i = 0; i < 100; i++) writedata();
    return 0;
}
+1

, :

static void writedata(int append);

int main()
{
    int i;

    /* Write data to file 100 times */
    for(i = 0; i < 100; i++) 
        writedata(i == 0);

    return 0;
}

static void writedata(int append)
{
    /* Create file for displaying output */
    FILE *data;
    data = fopen("output.dat", append ? "a" : "w");

    /* do other stuff */
    ...
}

, , .

, FILE * . , , .

0

How about this method:

void clear_file(const char *filename)
{ 
    FILE *output = fopen(filename, "w");
    fclose(output);
}

So, the file is opened for recording and automatically erased.

0
source

Source: https://habr.com/ru/post/1737563/


All Articles