C語言檔案操作函式open write用法速記

2021-06-07 23:26:28 字數 811 閱讀 4045

以前一直都是用fopen、fwrite等高階函式寫檔案,這次嘗試用open、write、close操作檔案。**如下:

int ret = ob_success;

int fd = open(config_file, o_wronly | o_creat | o_trunc, s_irwxu | s_irwxg | s_irwxo);

static const int64_t buf_len = 512;

int64_t pos = 0;

char buf[buf_len];

ssize_t size = 0;

const char * config_file = "my.conf";

if (0 >= fd)

else

}close(fd);

}

重點:

open(config_file, o_wronly | o_creat | o_trunc, s_irwxu  | s_irwxg | s_irwxo);

表示建立檔案,用於寫入。如果檔案已經存在,則先將檔案原有內容清空再寫。重點是後面s_irwxu | s_irwxg | s_irwxo這個引數,這裡它表示所有人都擁有對生成檔案的讀寫執行許可權。這個一般來說不會有什麼問題。可能遇到的問題是:

第一次學習寫open,引數可能不能一次搞對,比如,沒有帶第三個引數,那麼生成的檔案許可權也會不對,於是後繼再執行這個程式,就會有permission deny,無法覆蓋掉先前生成的檔案。解決方法是手動用sudo許可權刪除掉生成的檔案,重新執行正確的程式。

C語言檔案操作函式

1.fopen 開啟檔案 相關函式 open,fclose 表頭檔案 include 定義函式 file fopen const char path,const char mode 函式說明 引數path字串包含欲開啟的檔案路徑及檔名,引數mode字串則代表著流形態。mode有下列幾種形態字串 r ...

C語言檔案操作函式

有時候在除錯程式需要進行大量資料的輸入輸出時,如何還是採用scanf printf 的方式進行,那就苦逼了。萬一資料上有一些小改動,那就更苦逼了,所以還是用檔案來幫我們記錄下來,這樣在分析的時候才能更方便一些。再說了,什麼地方都需要用到檔案,所以這個也是個重要的操作啊!需要包含標頭檔案 來乙個小示例...

c語言檔案操作函式

1.fopen file fopen const char filename,const char mode filename檔案路徑 檔名,mode,檔案開啟方式。返回值,成功,返回檔案指標,失敗,返回null。mode的值 r rb 唯讀方式開啟乙個文字檔案,檔案不存在,報錯 w wb 寫方式開...