一、C++中流和流操作符
C++中把數據之間的傳輸操作稱為流,流既可以表示數據從內存傳送到某個載體或設備中,即輸出流,也可以表示數據從某個載體或設備傳送到內存緩沖區變量中,即輸入流。C++輸入輸出除了read和write函數,還提供流操作符,可以重在,輸入流操作符">>"和輸出流操作符"<<"。
- 標准I/O流:內存與標准輸入輸出設備之間信息的傳遞;《iostream》
- 文件I/O流:內存與外部文件之間信息的傳遞;《fstream》
- 字符串I/O流:內存變量與表示字符串流的字符數組之間信息的傳遞《sstream》
二、文件流的基本操作
1.確定文件打開的模式。可以選的模式主要有:
ios::in 為輸入(讀)而打開一個文件
ios::out 為輸出(寫)而打開文件
ios::ate 初始位置:文件尾
ios::app 所有輸出附加在文件末尾
ios::trunc 如果文件已存在則先刪除該文件
ios::binary 二進制方式
2.默認情況下是以文本的方式寫文件,並且會刪除原本文件中的數據,即ios::trunc
3.判斷文件是否正常打開。好的文件操作習慣是,每次打開一個文件后,在進行文件寫之前要判斷文件是否正常打開,使用的函數是is_open()。
4.文件寫。主要有下面三函數,<< 流操作符,寫一個字符put(),寫一塊數據write;
std::ostream::operator<<
std::ostream::put
std::ostream::write
5.文件讀。主要有流操作符>>,讀一個字符get,讀一行getline,讀文件中一塊read
std::istream::operator>>
istream& operator>> (int& val);
std::istream::getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
std::getline (string)
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
std::istream::read
istream& read (char* s, streamsize n);
std::istream::get
istream& get (char& c);
6.文件結尾的判斷 infile.eof()
7.文件關閉 infile.close()
8.文件定位 seekp(),seekg()
9.文件修改,見實例
1.1 文件寫
#include <string> #include <iostream> #include <fstream> using namespace std; int main() { /* * ios::app:添加,ios::trunc:如果文件存在,先刪除該文件(默認) * bios::binary 二進制方式讀寫,默認是文本方式 */ ofstream outfile("testfile.txt",ios::out | ios::trunc); if(!outfile.is_open()){ cerr << "file cannot open!" << endl; return -1; } outfile << "This is a test.\n"; outfile << 100 << endl; outfile.put('c'); // write a char. outfile.put('\n'); char buffer[1024] = "abc"; outfile.write(buffer,sizeof(buffer)); // write a block. outfile.close(); return 0; }
1.2 文件讀
#include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream infile("testfile.txt"); if (!infile.is_open()) { cerr << "file cannot open!" << endl; return -1; } //讀一個字符 char ch; infile.get(ch); //讀一個字符串 string word; infile >> word; //讀一行 常用 infile.seekg(0); string line; getline(infile, line); char buffer[1024]; infile.seekg(0); //定位到文件頭 infile.getline(buffer, sizeof(buffer)); //讀文件塊 infile.seekg(0); infile.read(buffer, sizeof(buffer)); //判斷文件結尾 infile.seekg(0); while (!infile.eof()) { getline(infile,line); // infile >> word; // infile.read(buffer,sizeof(buffer)); } infile.close(); return 0; }
1.3 文件內容修改
#include <fstream> using namespace std; int main() { fstream inOutFile("testfile.txt",ios::in | ios::out); inOutFile.seekg(50); inOutFile << "修改文件很容易!\n"; inOutFile.close(); return 0; }
