c++fstream::read只返回第一个字符

前言:我是一个没有经验的编码员,所以这可能是一个明显的错误。也像所有这些代码都被盗和拍打在一起,所以我声称没有这个代码的所有权。

系统:我使用的是 Windows 10 64 位。我在 Notepad++ 中编写代码并使用 MinGW G++ 进行编译。

我想要做什么:我试图将整个文件(BMP 格式)读入一个变量,并返回一个指向该变量的指针作为函数的返回。

发生了什么:该变量仅存储文件的第一个字符。

char* raw_data(std::string filename){
//100% non-stolen
    std::ifstream is (filename, std::ifstream::binary);
    if (is) {
        // get length of file:
        is.seekg (0, is.end);
        int length = is.tellg();
        is.seekg (0, is.beg);
        std::cout << is.tellg() << "n"; 
        
        char * buffer = new char [length];
        std::cout << "Reading " << length << " characters... n";
        // read data as a block:
        is.read (buffer,length);
        std::cout << "nn" << *buffer << "nn";
    
        if (is)
            {std::cout << "all characters read successfully.";}
        else
            {std::cout << "error: only " << is.gcount() << " could be read";}
        is.close();
        // ...buffer contains the entire file...
//101% non-stolen
        return {buffer};
    }
    return {};
}

调用函数的代码是

char * image_data = new char [image_size];
        image_data = raw_data("Bitmap.bmp");

这编译得很好,EXE 输出

0
Reading 2665949 characters...


B

all characters read successfully.

文件Bitmap.bmp开始:

BM¶ƒ     6   (   €  ‰        €ƒ ?  ?          ¨??¨??¨??¨

如您所见,变量缓冲区仅存储Bitmap.bmp的第一个字符(如果我更改第一个字符,它也会更改)

任何帮助,将不胜感激。感谢您的时间。

回答

std::cout << "nn" << *buffer << "nn";

缓冲区是一个char*,所以通过取消引用它,你得到一个单一的char,而你的情况是B.如果你想输出的整个数据,你看就是不取消引用指针,在C / C ++char*与outputing时特殊处理std::coutprintf诸如此类。

std::cout << "nn" << buffer << "nn";

请记住,按照惯例,输入的 C 字符串char*应该以 null 结尾,而您的则不是,并且您的函数的调用者没有有效的方法来检查它的长度,该信息会像strlen期望 Cstring 为空这样的函数一样丢失- 也终止了。您应该查看std::vector<char>std::string保存此类数据,因为它们将保存有关大小的信息,并自行清理。

  • Using iostream to output buffer will be rather meaningless due to nul-bytes in the binary file. Better to loop outputting the `unsigned char` hex value of each byte (or at least a headers worth [BMP file format](https://en.wikipedia.org/wiki/BMP_file_format))

以上是c++fstream::read只返回第一个字符的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>