fstream提供了三个类,用来实现c++对文件的操作(文件的创建、读、写)
文件打开模式:
标示 | 含义 |
---|---|
ios::in | 只读 |
ios::out | 只写 |
ios::app | 从文件末尾开始写,防止丢失文件中原来就有的内容 |
ios::binary | 二进制模式 |
ios::nocreate | 打开一个文件时,如果文件不存在,不创建文件 |
ios::noreplace | 打开一个文件时,如果文件不存在,创建该文件 |
ios::trunc | 打开一个文件,然后清空内容 |
ios::ate | 打开一个文件时,将位置移动到文件尾 |
使用代码举例:
ifstream infile; //输入流
ofstream outfile("test.txt", ios::out); //输出流
infile.open("data.txt", ios::in);
fstream fst("data.txt", ios::in | ios::out);
使用成员函数close,如:
f.close();
读取一行:
infile.getline(data, 100);
infile >> data;
在 C++ 编程中,使用流提取运算符( >> )从文件读取信息,就像使用该运算符从键盘输入信息一样。唯一不同的是,在这里使用的是 ifstream 或 fstream 对象.
写入一行:
outfile << data << endl;
使用流插入运算符( << )向文件写入信息.
// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)
fileObject.seekg( n );
// 把文件的读指针从 fileObject 当前位置向后移 n 个字节
fileObject.seekg( n, ios::cur );
// 把文件的读指针从 fileObject 末尾往回移 n 个字节
fileObject.seekg( n, ios::end );
// 定位到 fileObject 的末尾
fileObject.seekg( 0, ios::end );
int main() {
fstream picture_fp, rar_fp,output_fp;
char data;
string data2;
char picture_filename[50], rar_filename[50], output_filename[50];
cout << "Please input the picture name :" << endl;
cin>>picture_filename;
cout << "Please input the rar file name :" << endl;
cin >> rar_filename;
cout << "Please input the output file name :" << endl;
cin >> output_filename;
picture_fp.open(picture_filename, ios::in|ios::binary);
if (!picture_fp.is_open()) {
cout << "打开失败" << endl;
}
rar_fp.open(rar_filename, ios::in | ios::binary);
if (!rar_fp.is_open()) {
cout << "打开失败" << endl;
}
output_fp.open(output_filename, ios::out | ios::binary);
while (!picture_fp.eof())
{
data=picture_fp.get() ;//读一个字符
//picture_fp >> data2;//读一行
output_fp << data;
}
picture_fp.close();
while (!rar_fp.eof())
{
data=rar_fp.get() ;//读一行
output_fp << data;
}
rar_fp.close();
output_fp.close();
system("pause");
}