C语言 如何清除C中文件的全部内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4815251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:37:43  来源:igfitidea点击:

How do I clear the whole contents of a file in C?

cfilefile-iofile-handling

提问by mujahid

I have a file with some of user1's data. I want to use the same file for user2 by clearing the content of the file.

我有一个包含一些 user1 数据的文件。我想通过清除文件的内容为 user2 使用相同的文件。

My idea is that when a new user comes, data of the previous user should be clear and the same file should be ready for the new user.

我的想法是,当新用户到来时,前一个用户的数据应该是清晰的,并且应该为新用户准备好相同的文件。

回答by binW

As @stefan said using fopen()with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file.

正如@stefan 所说,使用fopen()“w”模式将为您完成这项工作。当您打开带有“w”标志的文件时,它会创建一个用于写入的空文件。如果已存在同名文件,则其内容将被删除,并将该文件视为空的新文件。

If the file is already open you can use freopen()function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.

如果文件已经打开,您可以使用freopen()带有“w”模式的 stdio.h 中的函数,因为它将首先关闭文件,然后重新打开它以写入擦除之前文件中的任何内容。

回答by stefan

with fopen(filename, flag)just open it with flag= "w"or "wb"and it will be cleared

fopen(filename, flag)只是标志打开="w"或者"wb",它会被清除

回答by Edward Karak

fclose(fopen("file.txt", "w"));

Why this works:

为什么这样做:

write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

write:为输出操作创建一个空文件。如果已存在同名文件,则丢弃其内容并将该文件视为新的空文件

(quote from http://www.cplusplus.com/reference/cstdio/fopen/)

(引自http://www.cplusplus.com/reference/cstdio/fopen/

回答by garvitlnmiit

There are two ways:

有两种方式:

1. fd=open(filename,O_RDONLY | O_WRONLY | O_TRUNC);


2. [cat /dev/null > filename] for BASH. It can be directly used in c program using [system()] system call. 

   system("cat /dev/null > filename");   

回答by pietervanderstar

I am using:

我在用:

fp=freopen(NULL,"w",fp);