C++中文件读写操作

image.png

fstreaml类

fstream提供了三个类,用来实现c++对文件的操作(文件的创建、读、写)

  1. fstream 文件流
  2. ifstream 输入文件流
  3. ofstream 输出文件流

打开文件

文件打开模式:

标示 含义
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");
}

参考

c++文件读写操作
C++ 文件和流

你可能感兴趣的:(C++中文件读写操作)