gpt4 book ai didi

C++ 以二进制模式读取文件。文件结束的问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:56:49 26 4
gpt4 key购买 nike

我正在学习 C++,我必须以二进制模式读取文件。以下是我的操作方法(遵循 C++ 引用):

unsigned values[255];
unsigned total;
ifstream in ("test.txt", ifstream::binary);

while(in.good()){
unsigned val = in.get();
if(in.good()){
values[val]++;
total++;
cout << val <<endl;
}
}

in.close();

所以,我逐字节读取文件,直到 in.good() 为真。我在 while 的末尾放置了一些 cout 以了解发生了什么,这是输出:

marco@iceland:~/workspace/huffman$ ./main 
97
97
97
97
10
98
98
10
99
99
99
99
10
100
100
10
101
101
10
221497852
marco@iceland:~/workspace/huffman$

现在,输入文件“test.txt”就是:

aaaa
bb
cccc
dd
ee

所以一切正常,直到最后,那里有 221497852。我猜这是关于文件结尾的问题,但我无法找出问题所在。

我在 debian 机器(64 位)上使用 gedit 和 g++。任何帮助将不胜感激。

非常感谢,

马可

最佳答案

fstream::get返回一个 int 值。这是问题之一。

其次,您正在阅读二进制,因此您不应该使用格式化流。你应该使用 fstream::read :

// read a file into memory
#include <iostream> // std::cout
#include <fstream> // std::ifstream

int main () {

std::ifstream is ("test.txt", std::ifstream::binary);
if (is) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);

char * buffer = new char [length];

std::cout << "Reading " << length << " characters... ";
// read data as a block:
is.read (buffer,length);

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...

delete[] buffer;
}
return 0;
}

关于C++ 以二进制模式读取文件。文件结束的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16435180/

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