我想知道如何用C清除文件的內容。我知道可以使用truncate
來完成,但我找不到任何清楚描述內容的來源。如何清除文件的內容
回答
其他答案解釋瞭如何正確使用truncate
......但是如果您發現自己在沒有unistd.h
的非POSIX系統上,那麼最簡單的方法就是打開文件進行寫入並立即關閉它:
#include <stdio.h>
int main()
{
FILE *file = fopen("asdf.txt", "w");
if (!file)
{
perror("Could not open file");
}
fclose(file);
return 0;
}
打開與"w"
文件(寫模式)「清空」文件,所以你可以開始覆蓋它;立即關閉它然後導致一個0長度的文件。
的truncate()
呼叫UNIX很簡單:
truncate("/some/path/file", 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;
}
如果你已經打開文件,可以使用該句柄與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;
}
對於刪除fie的內容顯然有一種在寫入模式「w」下打開文件的基本方法,然後在不做任何修改的情況下關閉它。
FILE *fp = fopen (file_path, "w");
fclose(fp);
這將刪除文件中的所有數據,當您使用「W」模式下的文件被刪除,並用相同名稱的新文件打開一個已經存在的文件爲寫而打開,這將導致到刪除您的文件的內容。
但截斷系統調用在UNIX系統上,這是專門爲同樣的目的,並很容易使用:
truncate (filepath, 0);
如果你已經打開了你的文件,所以無論你做之前關閉您的文件截斷或使用ftruncate
ftruncate (file_path, 0);
用'ftruncate'調用變量'file_path'是相當具有誤導性的。它應該被稱爲'fd'或者這樣的.. – 2010-07-03 14:21:48
截斷(2)是不是便攜式電話。它只符合4.2BSD。雖然它在大多數* nix類型的系統上都可以找到,但我會說使用符合POSIX.1的例程,這些例程在大多數現代環境(包括Windows)中都有很大的保證。
所以這裏是一個POSIX.1-2000兼容的代碼片段:
int truncate_file(const char *name) {
int fd;
fd = open (name, O_TRUNC|O_WRONLY);
if (fd >= 0)
close(fd); /* open can return 0 as a valid descriptor */
return fd;
}
錯誤,它已經在XSI選項中很長一段時間了,而且從POSIX 2008開始它就在基地。請參閱http://www.opengroup.org/onlinepubs/9699919799/functions/truncate.html – 2010-07-03 14:20:58
- 1. 清除文件的內容
- 2. 清除文本文件的內容
- 3. 如何清除/刪除matlab中的.txt文件的內容
- 4. 清除文件上傳的內容
- 5. 恢復已清除的文件內容
- 6. 清除cmd文件的內容
- 7. 我如何清除一個文本文件的內容在PHP
- 8. 無法清除文件內容
- 9. 如何使用c清除文件的內容?
- 10. 如何清除C文件中的全部內容?
- 11. Maven - 如何在清理階段刪除文件夾的內容?
- 12. 如何從VB中清除csv文件的內容
- 13. 如何清除佈局上的內容?
- 14. 如何清除NSMutableAttributedString的內容?
- 15. 如何清除jTable的內容?
- 16. 如何清除UIWebView/WKWebView的內容?
- 17. 如何清除「document.write()」所寫的內容
- 18. 如何清除IFRAME的內容?
- 19. 如何從php文件中清除錯誤日誌內容?
- 20. 如何清除/刪除Tkinter Text小部件的內容?
- 21. 清除DIV內容
- 22. 如何清除onclick div內容?
- 23. Ruby - 如何清除變量內容?
- 24. 清空文件內容
- 25. 清除面板的內容
- 26. 清除UIScrollView的內容
- 27. 清除列的內容
- 28. 清除char **中的內容
- 29. 清除NSMutableData中的內容
- 30. vb.net:清除System.Collections.ArrayList的內容?
'如果(!文件)PERROR( 「開放」);' – 2010-06-29 01:43:20
要完全安全的,檢查FCLOSE返回值也;) – Nyan 2010-06-29 06:53:30