开发者

Why do I get corrupt output on my file?

开发者 https://www.devze.com 2023-01-02 23:47 出处:网络
I have a simple program which I have compiled in both MinGW and Visual C++ 2008 Express, and both give an output file larger than 88200.When I set s = 0, 开发者_开发问答both programs work as expected.

I have a simple program which I have compiled in both MinGW and Visual C++ 2008 Express, and both give an output file larger than 88200. When I set s = 0, 开发者_开发问答both programs work as expected. What am I doing wrong?

#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    int i;
    short s;

    fstream f;

    f.open("test.raw", ios_base::out);

    for(i = 0; i < 44100; i++)
    {
        s = i & 0xFFFF; // PROBLEM?
        f.write(reinterpret_cast<const char *>(&s), sizeof(s));
    }

    f.close();

    return 0;
}


Try:

f.open("test.raw", ios_base::out | ios_base::binary);

When you write out chars that happen to match the newline character \n they are being converted to the standard windows newline sequence \r\n. Opening the file in binary mode stops this conversion from being performed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号