c++文件的讀寫 1.文本方式的寫文件 3.二進位方式的寫文件 c++ include include using namespace std; int main(){ int ar[] = {11,232,123123,1223,455,4,4,5,56,4,33}; ofstream ofile ...
c++文件的讀寫
1.文本方式的寫文件
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int ar[] = {1123,123,43,45,63,43,2,3};
//方法1,ios::out含義是也寫的方式打開流
ofstream ofile1("./test.txt", ios::out);
//方法2
ofstream ofile2;
ofile2.open("./test.txt");
if(!ofile1){//文件打開失敗
cerr << "open err" << endl;
exit(1);
}
for(int i = 0; i < sizeof(ar) / sizeof(int); ++i){
ofile1 << ar[i] << " ";
}
ofile1.close();
}
2.文本方式的讀文件
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int ar[10];
ifstream ifile("./test.txt",ios::in);
if(!ifile){
cerr << "open err" << endl;
exit(1);
}
for(int i = 0; i < 10; ++i){
//用空格分割讀進數組
ifile >> ar[i];
}
}
3.二進位方式的寫文件
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int ar[] = {11,232,123123,1223,455,4,4,5,56,4,33};
ofstream ofile("./text2.txt", ios::out | ios::binary);
if(!ofile){
cerr << "open err" << endl;
}
ofile.write((char*)ar, sizeof(ar));
ofile.close();
}
4.二進位方式的讀文件
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int ar[10];
ifstream ifile("./text2.txt",ios::in | ios::binary);
if(!ifile){
cerr << "open err" << endl;
}
ifile.read((char*)ar, sizeof(ar));
ifile.close();
}
5.按位置讀寫文件
- 文本方式的按位置讀
假設文件的內容:【1 12 222 3232 2232323】,每個數位元組數都不一樣,不能正確讀出想要的。
解決辦法,使用二進位方式的按位置讀。
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream ifile("./test.txt", ios::in);
if(!ifile){
cerr << "open err" << endl;
}
int index;
int value;
while(1){
cin >> index;
ifile.seekg(index, ios::beg); //移動指針
ifile >> value;
cout << value << endl;
}
}
- 進位方式的按位置讀
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream ifile("./test.txt", ios::in | ios::binary);
if(!ifile){
cerr << "open err" << endl;
}
int index;
int value;
while(1){
cin >> index;
ifile >> value;
cout << value << endl;
}
}
6.文件與對象的例子
在構造函數里讀取文件A,用文件A里的數據初始化對象;在析構函數里把對象的數據寫入文件A。
#include <iostream>
#include <fstream>
using namespace std;
class C{
friend ostream& operator<<(ostream&, const C&);
public:
C() : shi(0), xu(0){
ifstream ifile("./data.dat", ios::in);
if(!ifile){
cerr << "open err" << endl;
exit(1);
}
ifile >> shi >> xu;
ifile.close();
}
C(int i, int j) : shi(i), xu(j){}
~C(){
ofstream ofile("./data.dat", ios::out);
if(!ofile){
cerr << "open err" << endl;
exit(1);
}
ofile << shi << " " << xu;
ofile.close();
}
C(int i, int j) : shi(i), xu(j){}
~C(){
ofstream ofile("./data.dat", ios::out);
if(!ofile){
cerr << "open err" << endl;
exit(1);
}
ofile << shi << " " << xu;
ofile.close();
}
void setC(int i, int j){
shi = i;
xu = j;
}
private:
int shi;
int xu;
};
ostream& operator<<(ostream& out, const C& c){
out << "(" << c.shi << "," << c.xu << ")";
return out;
}
int main(){
C c;
cout << c << endl;
c.setC(10,22);
cout << c << endl;
}