ofstream写入文件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include<bits/stdc++.h> using namespace std;
int main() { string f_name="text.txt"; ofstream fout(f_name); if(!fout.is_open()){ cout<<"shibai"<<endl; return 1; } fout << "Hello, File!" << endl; fout << "数字:" << 123 << " 浮点数:" << 3.14 << endl; fout << "多行数据" << "\n"; fout.close(); cout << "数据写入成功!" << endl; return 0; }
|
ifstream读文件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include<bits/stdc++.h> using namespace std;
int main() { ifstream fin("text.txt"); if(!fin.is_open()){ return 1; }
string line2; string result; while(getline(fin,line2)){ result+=line2; result+='\n'; } cout<<result<<endl; fin.close(); }
|
文件打开再读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include<bits/stdc++.h> using namespace std;
int main() { string fn; cin>>fn;
ofstream fout(fn);
string a; cin>>a;
fout<<a; fout.close();
ifstream fin(fn); if(!fin.is_open()){ return 1; }
string s; while(getline(fin,s)){ cout<<s; }
fin.close();
return 0; }
|
追加文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| #include<bits/stdc++.h> using namespace std;
int main() { string fn="text.txt"; ifstream fin(fn); if(!fin.is_open()){ return 1; } string line; string result; while(getline(fin,line)){ result+=line; result+='\n'; } cout<<result; fin.close();
ofstream fout(fn,ios_base::out|ios_base::app); if(!fout.is_open()){ return 1; } string sss; cin>>sss; fout<<sss<<endl; fout.close();
fin.clear(); fin.open(fn); if(!fin.is_open()){ return 1; } string line2; string result2; while(getline(fin,line2)){ result2+=line2; result2+='\n'; } cout<<result2; fin.close(); return 0; }
|
二进制
二进制读写:
\1. 开模式:加binary(out/in | binary);
// 写模式+二进制模式:ios::out | ios::binary(记:out=写,binary=二进制) ofstream fout(fn, ios::out | ios::binary);
// 读模式+二进制模式:ios::in | ios::binary(in=读,可省略,默认就是读) ifstream fin(fn, ios::in | ios::binary);
\2. 写用write:(char*)&数据,sizeof算字节;
\3. 读用read:顺序字节全一致,字符串先读长度;
\4. 流程:创对象→查打开→关文件(和文本一样)。
打开一个文件加到另一个里面

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include<bits/stdc++.h> using namespace std;
int main() { string sfn="text.txt"; string efn="text2.txt"; ifstream fin(sfn); if(!fin.is_open()){ return 1; }
ofstream fout(efn); if(!fout.is_open()){ return 1; } string str; string result; while(getline(fin,str)){ fout<<str<<endl; } fin.close(); fout.close(); }
|