在C/C++ 讀寫檔案操作比較常見應該是利用 FILE、ifstream、ofstream
在這篇筆記裡頭記錄 FILE、fstream 使用方法及操作
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream> using namespace std; int main()
{
/*
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.
*/
FILE *pFile; /* open and create the file */
pFile = fopen("temp.txt", "w+");
char buffer[] = "write string test";
char *rd_buffer;
/* write the buffer to text file */
fwrite(buffer, sizeof(char), sizeof(buffer), pFile);
/* close file */
fclose(pFile); pFile = fopen("temp.txt", "r+");
/* assign read buffer size */
rd_buffer = (char*)malloc(sizeof(char)* sizeof(buffer));
/* read file data to read file */
fread(rd_buffer, sizeof(char), sizeof(buffer), pFile);
cout << rd_buffer << endl;
/* close file */
fclose(pFile); system("pause");
return ;
}
在開始進行讀寫之前有一段註解,裡頭主要標示在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, , pFile);
cout << data;
}
以下是fsteram 檔案基本操作,之後有遇到比較困難的應用在來上頭記錄
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream> using namespace std; int main()
{
fstream file; /* write file operation */
file.open("temp.txt", ios::out);
file << "write data to file" << endl;
file << "fstream write file to test" << endl;
file << "fstream line 1 test" << endl;
file << "fstream line 2 test" << endl;
file << "fstream line 3 test" << endl;
file << "fstream line 4 test" << endl;
file << "fstream line 5 test" << endl;
file << "fstream line 6 test" << endl;
file << "fstream line 7 test" << endl;
file << "fstream line 8 test" << endl;
file.close(); /* read file operation */
file.open("temp.txt", ios::in);
while (!file.eof()){
char buf[];
file.getline(buf, );
cout << buf << endl;
}
file.close(); system("pause");
return ;
}