二进制文件 I/O


使用二进制模式开启文件,在写入或读取文件时不会发生字符转换,数值在内存中的位是如何,写入文件时就是如何,而读入时也是相同。

下面这个程序可以读入任意文件,每次读入一个字节,并将读入数据以 16 进制数显示,若读入的数据前导位为 1,为了输出的对齐,使用其补数加以显示:

#include <iostream> 
#include <fstream> 
#include <iomanip> 
using namespace std; 

void print(ifstream &in) {
    char ch; 
    int count = 0;     
    while(!in.eof()) { 
        in.get(ch); 
        if(ch < 0) {
            ch = ~ch;     // 负数取补数 
        }
        cout << setw(2) << hex << static_cast<int>(ch) << " "; 
        count++; 
        if(count > 16) {  // 换行 
            cout << endl; 
            count = 0; 
        } 
    } 
    cout << endl; 
}

int main(int argc, char* argv[]) { 
    ifstream in(argv[1], ios::in | ios::binary); 
    if(!in) { 
        cout << "无法读取文件" << endl; 
        return 1; 
    } 

    print(in);
    in.close(); 

    return 0; 
}

执行结果:

23 69 6e 63 6c 75 64 65 20 3c 69 6f 73 74 72 65 61
6d 3e  a 23 69 6e 63 6c 75 64 65 20 3c 66 73 74 72
65 61 6d 3e  a 23 69 6e 63 6c 75 64 65 20 3c 69 6f
6d 61 6e 69 70 3e  a 75 73 69 6e 67 20 6e 61 6d 65
73 70 61 63 65 20 73 74 64 3b  a  a 69 6e 74 20 6d
61 69 6e 28 69 6e 74 20 61 72 67 63 2c 20 63 68 61
略....

下面这个程序可以让将文件复制至另一指定名称:

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(int argc, char* argv[]) { 
    char ch; 

    ifstream in(argv[1], ios::in | ios::binary); 
    ofstream out(argv[2], ios::out | ios::binary); 

    while(!in.eof()) { 
        in.get(ch); 
        if(!in.eof()) 
            out.put(ch); 
    } 

    in.close(); 
    out.close(); 

    return 0;
}

在写入或读取文件时,也可以用readwrite函数以区块的方式写入,它们的函数雏型如下:

istream &read(char *buf, streamsize num);
ostream &write(const char* buf, streamsize num);

其中num是要写入的数据字节数目,下面这个程序示范如何将数组数据写入文件,然后再将之读出:

#include <iostream> 
#include <fstream> 
using namespace std; 

int main(int argc, char* argv[]) { 
    ofstream out("temp", ios::out | ios::binary); 
    int arr[5] = {1, 2, 3, 4, 5}; 
    out.write(reinterpret_cast<char*>(arr), sizeof(arr)); 
    out.close(); 

    ifstream fin("temp", ios::in | ios::binary); 
    fin.read(reinterpret_cast<char*>(arr), sizeof(arr)); 
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << ' '; 
    }
    cout << endl; 
    fin.close(); 

    return 0; 
}




展开阅读全文