1.将数据写入文件
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream p1;
p1.open("outfile.txt");
p1 << "向文件写入信息" << endl;
p1.close();
return 0;
}
2.将数据从文件中读出
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char p[40];
ifstream p1;
p1.open("outfile.txt");
p1 >> p;
cout << p << endl;
p1.close();
return 0;
}
3.格式化输出读取一行
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char p[40];
ifstream p1;
p1.open("outfile.txt");
if (p1.fail())
{
return 0;
}
while (!p1.eof())
{
//读取一行,以#为分隔
p1.getline(p, 40, '#');
cout << p << endl;
}
p1.close();
return 0;
}
4.字符操作
instream.get( )获取一个字符
outstream.put( )写入一个字符
5.文件打开模式
6.流状态位
clear函数作用是所有标志位置为0.
7.二进制读写
- 在文本模式对整数199进行存储的时候,实际是对199的ASCII码方式'1','9',9' ----- 0x31 0x39 0x39 的方式进行存储的,占用3Byte,文本模式是建立在二进制读写的基础之上,只不过是将二进制信息进行了(字符编解码)。
- 如果以二进制进行存储的话占用了1Byte,使用十六进制C7表示,把int型转换成十六进制进行存储。
8.将任意类型数据写入文件
把数据需要转换为字节序列,即字节流;可以使用 reinterpret_cast(address)
1.写入操作
#include <iostream>
#include <armadillo>
#include <fstream>
using namespace std;
using namespace arma;
int main()
{
fstream binaryio;
binaryio.open("city.dat", ios::out | ios::binary);
int value = 199;
binaryio.write(reinterpret_cast<char*>(&value), sizeof(value));
binaryio.close();
cout << "Done" << endl;
return 0;
}
2.读取操作
#include <iostream>
#include <armadillo>
#include <fstream>
using namespace std;
using namespace arma;
int main()
{
fstream binaryio;
binaryio.open("city.dat", ios::in | ios::binary);
int value;
binaryio.read(reinterpret_cast<char*>(&value), sizeof(value));
binaryio.close();
cout << value << endl;
return 0;
}
3.二进制写入与读取数组
#include <iostream>
#include <armadillo>
#include <fstream>
using namespace std;
using namespace arma;
#define SIZE 5
int main()
{
//二进制写入数组
double array[SIZE] = { 3.4 , 1.3 , 2.5 , 5.66 , 6.9 };
fstream binaryio;
binaryio.open("city.dat", ios::out | ios::binary);
binaryio.write(reinterpret_cast<char*>(&array), sizeof(array));
binaryio.close();
//二进制读取数组
double result[SIZE];
binaryio.open("city.dat", ios::in | ios::binary);
binaryio.read(reinterpret_cast<char*>(&result), sizeof(array));
binaryio.close();
for (int i = 0; i < SIZE; i++)
{
cout << result[i] << endl;
}
return 0;
}