gpt4 book ai didi

c++ - 无法读取整个文件

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:18 24 4
gpt4 key购买 nike

我正在编写一个 C++ 程序,以便能够打开 .bmp 图像,然后能够将其放入二维数组中。现在我有这样的代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "Image.h"
using namespace std;

struct colour{
int red;
int green;
int blue;
};

Image::Image(string location){

fstream stream;
string tempStr;

stringstream strstr;
stream.open(location);

string completeStr;

while(!stream.eof()){
getline(stream, tempStr);
completeStr.append(tempStr);
}
cout << endl << completeStr;

Image::length = completeStr[0x13]*256 + completeStr[0x12];
Image::width = completeStr[0x17]*256 + completeStr[0x16];
cout << Image::length;
cout << Image::width;
cout << completeStr.length();

int hexInt;
int x = 0x36;
while(x < completeStr.length()){
strstr << noskipws << completeStr[x];
cout << x << ": ";
hexInt = strstr.get();
cout << hex << hexInt << " ";
if((x + 1)%3 == 0){
cout << endl;
}
x++;
}
}

现在,如果我在我的 256x256 测试文件上运行它,它将打印正常,直到它到达 0x36E,它给出错误/不再继续。发生这种情况是因为 completeStr 字符串没有收到 bmp 文件中的所有数据。为什么无法读取 bmp 文件中的所有行?

最佳答案

您的代码存在许多问题。校长一个(可能是你的问题的原因)是你以文本模式打开文件。从技术上讲,这意味着如果该文件包含除可打印字符之外的任何内容和一些特定的控制字符(如'\t'),你有未定义行为。实际上,在 Windows 下,这意味着序列0x0D, 0x0A 将被转换为单个 '\n',并且0x1A 将被解释为文件的结尾。并不真地读取二进制数据时想要什么。你应该打开以二进制模式流式传输 (std::ios_base::binary)。

这不是一个严重的错误,但你真的不应该使用 fstream如果您只打算读取文件。事实上,使用一个fstream 应该很少见:您应该使用 ifstreamofstream。同样的事情也适用于 stringstream(但是读取二进制文件时,我看不到 stringstream 的任何作用文件)。

此外(这是一个真正的错误),您正在使用的结果getline 不检查是否成功。通常阅读台词的成语是:

while ( std::getline( source, ling ) ) ...

但是像 stringstream 一样,您想在上使用 getline二进制流;它将删除所有的 '\n'(有已经从 CRLF 映射)。

如果你想要内存中的所有数据,最简单的解决方案是像这样的东西:

std::ifstream source( location.c_str(), std::ios_base::binary );
if ( !source.is_open() ) {
// error handling...
}
std::vector<char> image( (std::istreambuf_iterator<char>( source ) ),
(std::istreambuf_iterator<char>()) );

关于c++ - 无法读取整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15839977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com