2010-06-29 98 views

回答

12

其他答案解釋瞭如何正確使用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長度的文件。

+1

'如果(!文件)PERROR( 「開放」);' – 2010-06-29 01:43:20

+0

要完全安全的,檢查FCLOSE返回值也;) – Nyan 2010-06-29 06:53:30

5

truncate()呼叫UNIX很簡單:

truncate("/some/path/file", 0); 
3

雖然你可以打開和關閉文件時,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; 
} 
+0

指針(指向FILE)與整數比較? – Nyan 2010-06-29 06:54:18

+0

Ack,趕上! – fmark 2010-06-29 07:26:23

+0

'ftruncate'不需要'FILE *'參數。應該是'ftruncate(fileno(file),0)'..但是我質疑截斷文件的智慧,當你打開文件使用stdio函數。如果你的程序使用stdio而不是POSIX文件描述符函數,你應該關閉並重新打開''w「'模式文件來截斷它。 – 2010-07-03 14:23:27

1

對於刪除fie的內容顯然有一種在寫入模式「w」下打開文件的基本方法,然後在不做任何修改的情況下關閉它。

FILE *fp = fopen (file_path, "w"); 

fclose(fp); 

這將刪除文件中的所有數據,當您使用「W」模式下的文件被刪除,並用相同名稱的新文件打開一個已經存在的文件爲寫而打開,這將導致到刪除您的文件的內容。

但截斷系統調用在UNIX系統上,這是專門爲同樣的目的,並很容易使用:

truncate (filepath, 0); 

如果你已經打開了你的文件,所以無論你做之前關閉您的文件截斷或使用ftruncate

ftruncate (file_path, 0); 
+1

用'ftruncate'調用變量'file_path'是相當具有誤導性的。它應該被稱爲'fd'或者這樣的.. – 2010-07-03 14:21:48

1

截斷(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; 
} 
+1

錯誤,它已經在XSI選項中很長一段時間了,而且從POSIX 2008開始它就在基地。請參閱http://www.opengroup.org/onlinepubs/9699919799/functions/truncate.html – 2010-07-03 14:20:58