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长度的文件.
虽然您只能打开和关闭文件,但该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)