一窑睁、單個讀入讀出
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream ifs("./string.cpp");
if(ifs){// 判斷文件流對象是否ok
string s;
while(!ifs.eof()){//判斷文件是否結束
ifs >> s;
cout << s << endl;
}
}else{
cerr << "文件打開失敗" << endl;
}
// ifs.close();
// ...此處有處理
// ifs.open();
ofstream ofs("./test.txt");
if(ofs){
ofs << "abc" << 123 << endl;
}else{
cerr << "文件打開失敗" << endl;
}
}
二、可打開關閉
打開文加托慨,然后給一個文件名fs(文件路徑鼻由,ios::輸入 | ios:: 輸出)
- 判斷是否打開了文件
- 打開了則定一個string s;的字符串,,s作為接受信息的字符串
- 循環(huán)讀出文件里的東西fs >> s
- 然后打印在終端 cout << s << endl;
- 由于此時讀取指針指在了eof接下來是什么都讀不出來的所以要清除eof標志以便接下來的寫入操作
- 循環(huán)寫入操作 cin >> s;
- 將終端字符串讀如到字符串中
- 然后將s寫入到fs對應的文件中fs << s << endl;
#include <iostream>
#include <fstream>
using namespace std;
int main (){
fstream fs("./test.txt",ios::in | ios::out);
if(fs){
string s;
while(fs >> s){
cout << s << endl;
}
fs.clear();
while(cin >> s){
fs << s << endl;
}
cout << "s:" << s << endl;
}else{
cerr << "打開文件失敗" << endl;
}
}