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

醉酒当歌 提交于 2019-11-27 02:35:07

问题


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.

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.


回答1:


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.

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.




回答2:


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




回答3:


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.

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




回答4:


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");   



回答5:


I am using:

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


来源:https://stackoverflow.com/questions/4815251/how-do-i-clear-the-whole-contents-of-a-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!