1. 程式人生 > >(C/C++) FILE 讀寫檔案操作

(C/C++) FILE 讀寫檔案操作

per use () eat col 在操作 har 意思 etl

在C/C++ 讀寫檔案操作比較常見應該是利用 FILE、ifstream、ofstream

在這篇筆記裡頭記錄 FILE、fstream 使用方法及操作

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <fstream>
 5 
 6 using namespace std;
 7 
 8 
 9 int main()
10 {
11     /*
12         r : open for reading
13         rb : open for reading in binary mode
14 w : open for writing 15 wb : open for writing in binary mode 16 r+ : support read and write. the file must exit. 17 w+ : it like r+ funciton that will recover the file with same file name if file name exit. 18 */ 19 FILE *pFile; 20 21 /* open and create the file
*/ 22 pFile = fopen("temp.txt", "w+"); 23 char buffer[] = "write string test"; 24 char *rd_buffer; 25 /* write the buffer to text file */ 26 fwrite(buffer, sizeof(char), sizeof(buffer), pFile); 27 /* close file */ 28 fclose(pFile); 29 30 pFile = fopen("temp.txt", "r+"); 31
/* assign read buffer size */ 32 rd_buffer = (char*)malloc(sizeof(char)* sizeof(buffer)); 33 /* read file data to read file */ 34 fread(rd_buffer, sizeof(char), sizeof(buffer), pFile); 35 cout << rd_buffer << endl; 36 /* close file */ 37 fclose(pFile); 38 39 system("pause"); 40 return 0; 41 }

在開始進行讀寫之前有一段註解,裡頭主要標示在fopen開檔之後必須填入的參數代表啥意思

    /*
        r : open for reading
        rb : open for reading in binary mode
        w : open for writing
        wb : open for writing in binary mode
        r+ : support read and write. the file must exit.
        w+ : it like r+ funciton that will recover the file with same file name if file name exit.
    */

w/r 就很簡易的只是 : 只能讀 / 只能寫,wb/rb 多個b表示2進制的檔案操作

r+/w+ 多+ : 在操作上就是能讀能寫但是 r+ 有囑意是這個檔案必須存在

在讀檔案的時,有時需求是直接讀一行,利用feof函式去判斷是否讀到最後一行

while (!feof(pFile))
{
    fgets(data, 500, pFile);
    cout << data;
}

以下是fsteram 檔案基本操作,之後有遇到比較困難的應用在來上頭記錄

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <iostream>
 5 #include <fstream>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     fstream file;
12 
13     /* write file operation */
14     file.open("temp.txt", ios::out);
15     file << "write data to file" << endl;
16     file << "fstream write file to test" << endl;
17     file << "fstream line 1 test" << endl;
18     file << "fstream line 2 test" << endl;
19     file << "fstream line 3 test" << endl;
20     file << "fstream line 4 test" << endl;
21     file << "fstream line 5 test" << endl;
22     file << "fstream line 6 test" << endl;
23     file << "fstream line 7 test" << endl;
24     file << "fstream line 8 test" << endl;
25     file.close();
26 
27     /* read file operation */
28     file.open("temp.txt", ios::in);
29     while (!file.eof()){
30         char buf[200];
31         file.getline(buf, 200);
32         cout << buf << endl;
33     }
34     file.close();
35 
36     system("pause");
37     return 0;
38 }

(C/C++) FILE 讀寫檔案操作