在C++中写入二进制文件时出错

发布于 2024-11-01 17:24:35 字数 1231 浏览 2 评论 0原文

我尝试打开一个二进制文件进行读写(标志:ios_base::binary | ios_base::in | ios_base::out)。

我的文件已经存在,其内容为:123

读取文件没有问题,但关闭文件后写入文件不起作用。文件内容没有变化。看来 fstream.write() 无法正常工作。

我用的是VS2010。

代码:

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

int main (void) 
{
    fstream stream;

    // Opening the file: binary + read + write.
    // Content of file is: 123
    stream.open("D:\\sample.txt", ios_base::binary | ios_base::in | ios_base::out);

    // Read 1 bye.
    char ch;
    stream.read(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Check ch.
    // Content of file was: 123
    if(ch == '1')
    {
        cout << "It is correct" << endl;
    }

    // Write 1 bye.
    ch = 'Z';
    stream.write(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Close the file.
    stream.close();

    // OHhhhhhhhhhh:
    // The content of file should be: 1Z3
    // but it is: 123

    return 0;
}

谢谢。

抱歉我的英语不好:-)

I try to open a binary file for both reading and writing (flag: ios_base::binary | ios_base::in | ios_base::out).

My file already exists and its content is: 123

There is no problem in reading of the file, but writing the file does not work after closing the file. The file content has no change. It seems fstream.write() does not work correctly.

I use VS2010.

Code:

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

int main (void) 
{
    fstream stream;

    // Opening the file: binary + read + write.
    // Content of file is: 123
    stream.open("D:\\sample.txt", ios_base::binary | ios_base::in | ios_base::out);

    // Read 1 bye.
    char ch;
    stream.read(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Check ch.
    // Content of file was: 123
    if(ch == '1')
    {
        cout << "It is correct" << endl;
    }

    // Write 1 bye.
    ch = 'Z';
    stream.write(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Close the file.
    stream.close();

    // OHhhhhhhhhhh:
    // The content of file should be: 1Z3
    // but it is: 123

    return 0;
}

Thanks.

Sorry for my pooooooor English :-)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2024-11-08 17:24:36

您需要正确定位写入指针:

stream.seekp( 1 );
stream.write(&ch, 1/*size*/);

You need to position the write pointer correcty:

stream.seekp( 1 );
stream.write(&ch, 1/*size*/);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文