第五篇:使用無緩衝IO函式讀寫檔案

穆晨發表於2017-01-28

前言

       本文介紹使用無緩衝IO函式進行檔案讀寫。

       所謂的無緩衝是指該IO函式通過呼叫系統呼叫實現,其實系統呼叫內部的讀寫實現也是使用了緩衝技術的。

讀寫步驟

       1. 開啟檔案  open 函式

       2. 讀寫檔案  read write 函式

       3. 修改檔案指標  lseek 函式  ( 可能和 2 交替進行 )

       4. 關閉檔案  close 函式

程式碼示例

 1 //
 2 // 本程式往一個檔案中寫入一個整型陣列
 3 // 然後讀取這個陣列並輸出
 4 //
 5 
 6 #include <unistd.h>
 7 #include <fcntl.h>
 8 #include <errno.h>
 9 #include <iostream>
10 #include <string>
11 
12 using namespace std;
13 
14 const int LEN=5;
15 
16 int main(void) {
17     string filename; 
18     cout << "請輸入要處理的檔名: ";
19     cin >> filename;
20 
21     // 開啟 filename 檔案。
22     // 注意:
23     //    1. 第一個引數必須轉換成C的字串格式
24     //    2. 如果找不到檔案,就會以 777 許可權建立一個新的檔案。
25     //    3. 如果要進行讀寫,還要使用O_RDWR引數。
26     int fd = 0;
27     if (!(fd = open(filename.c_str(), O_CREAT|O_EXCL|O_RDWR, 777))) {
28         cout << "開啟/建立檔案失敗" << endl;
29         return 1;
30     }
31 
32     // 初始化測試陣列
33     int buf[LEN];
34     for (int i=0; i<LEN; i++) {
35         buf[i] = i;
36     }
37 
38     // 將陣列中的資料寫入到開啟的檔案中
39     if (write(fd, buf, LEN*sizeof(int)) != LEN*sizeof(int)) {
40         cout << "寫入失敗" << endl;
41         return 2;
42     }
43 
44     // 寫入指標回退兩個位置
45     lseek(fd, -2*sizeof(int), SEEK_CUR);
46 
47     // 繼續寫入資料 
48     if (write(fd, buf, LEN*sizeof(int)) != LEN*sizeof(int)) {
49         cout << "寫入失敗" << endl;
50         return 2;
51     }
52 
53     // 寫入指標回到檔案頂部
54     lseek(fd, 0, SEEK_SET);
55 
56     // 從檔案中讀取資料並輸出到標準輸出
57     int n=0;
58     while ((n = read(fd, buf, LEN*sizeof(int))) > 0) {
59         // 這裡切記不能夠直接用write輸出到標準輸入,因為write不知道陣列裡面放的資料是什麼型別。
60         for (int i=0; i<n/sizeof(int); i++) {
61             cout << buf[i] << " ";
62         }
63         cout << endl;
64     }
65     if (n<0) {
66         cout << "讀入失敗" << endl;
67         return 3;
68     }
69 
70     // 關閉檔案
71     close(fd);
72 
73     return 0;
74 }

小結

       1. read 和 write 函式是以二進位制的方式讀/寫,函式本身是不會去識別資料格式的。

       2. 當程式語句比較長的時候,要注意算符的優先順序。( 參考程式碼 58 行 )

       3. 使用完檔案之後記得關閉檔案描述符

相關文章