Reading and writing binary file

前端 未结 7 663
挽巷
挽巷 2020-11-22 16:29

I\'m trying to write code to read a binary file into a buffer, then write the buffer to another file. I have the following code, but the buffer only stores a couple of ASCI

7条回答
  •  一整个雨季
    2020-11-22 16:44

    There is a much simpler way. This does not care if it is binary or text file.

    Use noskipws.

    char buf[SZ];
    ifstream f("file");
    int i;
    for(i=0; f >> noskipws >> buffer[i]; i++);
    ofstream f2("writeto");
    for(int j=0; j < i; j++) f2 << noskipws << buffer[j];
    

    Or you can just use string instead of the buffer.

    string s; char c;
    ifstream f("image.jpg");
    while(f >> noskipws >> c) s += c;
    ofstream f2("copy.jpg");
    f2 << s;
    

    normally stream skips white space characters like space or new line, tab and all other control characters. But noskipws makes all the characters transferred. So this will not only copy a text file but also a binary file. And stream uses buffer internally, I assume the speed won't be slow.

提交回复
热议问题