How to delete the contents of a file in c?

0

How can I delete the contents of a file in c, what function should I use?

#include <stdio.h>
#include <stdlib.h>

void main(){
    char hello[13] = "Hello World!";
    char path[12] = "arquivo.txt";
    FILE* arquivo;
    arquivo = fopen(path, "a+");
    fprintf(arquivo, hello);
    printf("%s foi adicionado ao arquivo %s", hello, path);

    /*

    arquivo = fopen(path, "w");
    fclose(arquivo);

    */
}
    
asked by anonymous 27.09.2017 / 01:53

1 answer

3

To delete the contents of a file in C just open with w mode:

fopen(caminho_para_o_arquivo, "w");

Now in your case it happens that you already opened it previously with a+ :

void main(){
    ...
    arquivo = fopen(path, "a+");
    ...
    arquivo = fopen(path, "w");
    fclose(arquivo);
}

So the second try opening does not delete the content. To fix, put a fclose before opening again:

    arquivo = fopen(path, "a+");
    fclose(arquivo);
    ...
    arquivo = fopen(path, "w");
    fclose(arquivo);

Or even open to add content with a+ since it will then delete! Simplify and leave only:

fclose(fopen(path, "w"));
    
27.09.2017 / 02:23