标签:TE 解决办法 内容 IV for 读写文件 fstream cer main
#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();
}
#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];
}
}
#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();
}
#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();
}
假设文件的内容:【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;
}
}
标签:TE 解决办法 内容 IV for 读写文件 fstream cer main
原文地址:https://www.cnblogs.com/xiaoshiwang/p/9142301.html