【问题标题】:C++ what's happening with my ifstream.get() function?C++ 我的 ifstream.get() 函数发生了什么?
【发布时间】:2016-08-07 00:18:55
【问题描述】:

我正在尝试读取图片文件。

#include <iostream>
#include <fstream>

using namespace std;


int main()
{

    ifstream read("C://Users/Ben/Desktop/1.jpg");

    while (1){
        cout << read.get();
        cin.get();
    }


    return 0;
}

当我这样做时,我得到一系列从 0 到 255 的数字。所以我假设它正确读取字节值,除了我过早地点击 -1 (eof) 的事实。在大约 30 到 40 个值之后,出现 -1。这是一个 3MB 的文件。我不希望 -1 会在以后出现。怎么回事?

【问题讨论】:

  • 您可能需要在打开文件时指定二进制模式(C 中的fopen(file, "rb");我不知道如何处理流)。
  • ifstream::traits_type::eof() 不一定会评估为-1,但即使它确实如此,如果文件中有任何0xFF 字节,您认为输出会是什么?
  • 您还没有以二进制模式打开文件。尝试为 ios_base::in | ios_base::binary 形式的构造函数提供第二个参数。
  • 这绝对不是加载和读取 jpg 格式图像的方法。您看到的(预期)值不一定是像素(如果这是您的想法)。对于您得到的-1,它可能是unsigned char 255,而您将其阅读为signed,即-1
  • get() 的这个变体返回int,保证能够表示255 的值。

标签: c++ ifstream


【解决方案1】:

作为@melpomene mentioned in their commentstd::ifstream::get() 的结果可能会有所不同,因为文件是使用std::ios::binary 模式打开的(至少对于 Windows 操作系统来说是这样)。

没有证据表明 -1 的值作为 std::ifstream::get() 的结果表明 read 流处于 std::ifstream::eof() 状态。您可以阅读std::ifstream::get() 参考文档以获取更多信息。

【讨论】:

    【解决方案2】:

    试试这个

    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
    
        // Add the mode ios::binary to make the file load in binary format.
    
        ifstream read("C://Users/Ben/Desktop/1.jpg", ios::binary);
    
        // Declare data variable
    
        int data = 0;
    
        // Reading loop
    
        while (read.read((char*)&data, 4) && read.gcount() != 0) {
    
            // Output data
    
            cout << data << endl;
        }
    
        // Wait for user input before closing program
    
        cin.get();
    
        return 0;
    }
    

    【讨论】:

    • 和这里一样:stackoverflow.com/a/38809885/1413395 不幸的是你看不到:P
    • 深红妻子:泰!我试过了,它奏效了。但我做了一些修改。我声明了一个int变量'A',然后在while循环中将它实例化为A = read.get();但是当我这样做时,这意味着 A 一次读取 4 个字节,因为 int 的大小为 4 个字节。但是为什么我得到的值在 0~255 之间呢?它们不应该在 0~2^32 之间吗?
    • 抱歉,图像处理不是我的专业水平。
    • 我只是在这里猜测,但我会假设输出数字 (0~255) 是您的图像@Benn 的 rgb 颜色。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2014-01-25
    相关资源
    最近更新 更多