【问题标题】:C++ file i/o error?C++ 文件 i/o 错误?
【发布时间】:2011-03-31 08:09:16
【问题描述】:

为什么所有内容都被读取为 0?

    int width = 5;
    int height = 5;
    int someTile = 1;
    char buff[128];


    ifstream file("test.txt", ios::in|ios::binary);

    if(file.is_open())
    {
        cout << "open";
    }

    file.read(buff, sizeof(int));
    width = atoi(buff);

    file.read(buff, sizeof(int));
    height = atoi(buff);

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            file.read(buff, sizeof(int));
            someTile = atoi(buff);
            cout << someTile;
        }
    }

我的文件格式代码是用 C# 编写的:

FileStream stream = new FileStream("test.txt", FileMode.Create);
            BinaryWriter writer = new BinaryWriter(stream);
            // write a line of text to the file

            writer.Write(15);
            writer.Write(5);

            for (int i = 0; i < 15; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    writer.Write(1);
                }
            }

            // close the stream
            writer.Close();

【问题讨论】:

  • 不要吹毛求疵,但你不需要带有 ifstream 的 ios::in,它已经被定义为输入。如果您的文件打开失败,您仍然尝试读取数据会发生什么。
  • 您似乎以二进制模式打开文件,然后像处理文本一样处理数据。为什么不首先以文本模式打开文件?
  • 我可能有一个更简单的解决方案,但由于我不确定,我发布了它as a question

标签: c# c++ file io


【解决方案1】:

在不知道 test.txt 的内容的情况下很难准确地说出,但看起来您正在反复将 4 个字节(大多数平台上的 int 大小)读入字符缓冲区/字符串,然后尝试将其转换为成一个数。除非您的文件完全由以 null 结尾的四个字节块构成,否则我不希望这会起作用。

更新:好的,看看你的文件格式,你不是在写字符串,而是在写整数。因此,我希望您能够直接读取您的数字,而无需 atoi

例如:

int value;
file.read((char*)&value, sizeof(int));

value 现在应该包含文件中的数字。要转换你的整个例子,你正在寻找这样的东西:

int width = 5;
int height = 5;
int someTile = 1;

ifstream file("test.txt", ios::in|ios::binary);

if(file.is_open())
{
    cout << "open";

    file.read(reinterpret_cast<char*>(&width), sizeof(int));
    file.read(reinterpret_cast<char*>(&height), sizeof(int));

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            file.read(reinterpret_cast<char*>(&someTime), sizeof(int));
            cout << someTile;
        }
    }
}

【讨论】:

  • |45|error: no matching function for call to 'std::basic_ifstream >::read(int*, unsigned int)'
  • 当我尝试那个时仍然得到同样的错误。没有匹配函数调用 'std::basic_ifstream >::read(int*, unsigned int)'
  • 好的,看起来我需要一些强制转换来用于 ifstream,但没有意识到它只有 char* 方法。我更喜欢使用普通的fopen/fread 进行 IO。看看这是否有效。
  • 注意:上述方法不可移植
  • @Simon,那个和大/小字节序。
【解决方案2】:

atoi 将 NUL 终止的字符串转换为整数 - 您正在从文件中读取四个 字节(它处于二进制模式) - 这可能不正确..

例如,一个有效的字符串(atoi 工作可能是,“1234” - 注意:NUL 终止),但是它的字节表示是 0x31 0x32 0x33 0x34(注意 NUL 终止,因为你只读取了 4 个字节,所以,atoi 可以做任何事情)。这个文件的格式是什么?如果它真的是字节表示,数字 1234 看起来像(取决于字节序),0x00 0x00 0x04 0xD2,正确读取此int 的方法是逐字节移动。

那么,一个大问题 - 格式是什么?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多