2016-06-21 36 views
0

我使用open()函數打開文件。如何使open()截斷現有文件

我想open()函數丟棄文件內容,如果它已經存在,然後該文件被視爲一個新的空文件。

我試着用下面的代碼:

int open_file(char *filename) 
{ 
    int fd = -1; 
    fd = open(filename, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); 
    if (fd < 0) { 
     printf("Couldn't create new file %s: %s\n", 
      filename, strerror(errno)); 
     return -1; 
    } 
    close(fd); 
    return 0; 
} 

,但我得到了以下錯誤:

Couldn't create new file kallel333: File exists 

我缺少什麼?

+0

要刪除或截斷文件 – sas

+4

您是否嘗試添加O_TRUNC標誌。 – sas

+0

@sas watever,目標是有一個新的空的打開的文件。我不想得到這個錯誤 – MOHAMED

回答

5

請添加O_TRUNC標誌和刪除O_EXCL。

open(filename, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR); 

從開手冊頁 -

O_EXCL確保這個調用創建文件:如果該標誌與O_CREAT一起指定 ,和路徑已經 存在,則open()將失敗。

O_TRUNC 如果該文件已經存在,並且是一個普通文件和 訪問模式允許寫入(即,是或O_RDWR O_WRONLY)它 將被截斷爲長度

2

open()的手冊頁說,這對O_TRUNC標誌:

O_TRUNC If the file already exists and is a regular file and the open mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise the effect of O_TRUNC is unspecified.

+0

這就是它的一部分 - 但只是其中的一部分。您也必須刪除'O_EXCL',因爲如果它存在,那麼在截斷有機會發生之前,如果文件已經存在,系統調用將無法打開該文件。請注意,如果可能,最好提供一個指向您諮詢的手冊頁的在線版本的鏈接。對於Linux,您通常可以使用http://linux.die.net/作爲手冊頁的源代碼 - 儘管有很多選擇。 –

3

的問題是O_EXCL標誌。從手冊頁open(2)

O_EXCL Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists, then open() will fail.

我建議刪除O_EXCL,增加O_TRUNC,並再次嘗試。

0

我會告訴你這個錯誤是什麼! Open函數將具有返回類型,即執行此係統調用後會返回一些值(在您的情況下,它將存儲在fd中)。 該值將指示系統調用的執行是否成功。當open系統調用失敗時,會自動返回-1(至fd),您已在函數int fd = -1;的第一個語句中初始化它。因此,if (fd < 0)語句被驗證爲正確,因此您正在收到該錯誤。 請注意,您不應設置系統調用的返回值,它們將在程序執行時自動返回。你需要做的只是確保你捕獲這個值並驗證它。因此,請將您的第一條語句int fd = -1更改爲int fd

底線:您設置open系統調用的返回值,從而-1 ,告訴它的創作應該不惜任何代價失敗的編譯器!就權限而言,請參閱其他評論!:)