如何清除文件的内容

mou*_*sey 4 c unix

我想知道如何在C中清除文件的内容.我知道它可以使用truncate,但我找不到任何清楚描述如何的源.

Mar*_*off 12

其他答案解释了如何truncate正确使用...但如果你发现自己在一个没有的非POSIX系统上unistd.h,那么最简单的方法就是打开文件写入并立即关闭它:

#include <stdio.h>

int main()
{
    FILE *file = fopen("asdf.txt", "w");
    if (!file)
    {
        perror("Could not open file");
    }

    fclose(file);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用"w"(用于写入模式)打开文件"清空"文件,以便您可以开始覆盖它; 然后立即关闭它会产生一个0长度的文件.


caf*_*caf 5

truncate()UNIX中的调用很简单:

truncate("/some/path/file", 0);
Run Code Online (Sandbox Code Playgroud)


fma*_*ark 5

虽然您只能打开和关闭文件,但该truncate调用是专门针对此用例而设计的:

#include <unistd.h> //for truncate
#include <stdio.h>  //for perror

int main()
{
    if (truncate("/home/fmark/file.txt", 0) == -1){
      perror("Could not truncate")
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您已经打开了文件,则可以使用该句柄ftruncate

#include <stdio.h>  //for fopen, perror
#include <unistd.h> //for ftruncate

int main()
{
    FILE *file = fopen("asdf.txt", "r+");
    if (file == NULL) {
        perror("could not open file");
    }

    //do something with the contents of file

    if (ftruncate(file, 0) == -1){
          perror("Could not truncate")
    }

    fclose(file);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • `ftruncate` 不接受 `FILE *` 参数。应该是 `ftruncate(fileno(file),0)`.. 但我质疑在打开文件以与 stdio 函数一起使用时截断文件是否明智。如果您的程序使用 stdio 而不是 POSIX 文件描述符函数,您可能应该关闭并以“w”模式重新打开文件以截断它。 (2认同)