How to delete the contents of a file in c?

Asked

Viewed 4,313 times

0

How can I delete the contents of a file in c, which 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);

    */
}
  • All content?

  • yes, delete all content from a text file

  • 2

    Open the file in mode w does not delete the previous content?

  • It’s literally just doing fopen with w as @Andersoncarloswoss said

  • I tried to open with w, but it didn’t erase

  • 1

    And why not delete the file purely and simply?

Show 1 more comment

1 answer

3


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

fopen(caminho_para_o_arquivo, "w");

Now in your case it turns out you’ve opened it previously with a+:

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

Hence the second opening attempt does not delete the content. To correct put a fclose before opening again:

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

Or better not open to add content with a+ since then will erase! Simplify and leave only:

fclose(fopen(path, "w"));
  • I created this code just to simplify things, now it worked, thank you Isac

Browser other questions tagged

You are not signed in. Login or sign up in order to post.