gpt4 book ai didi

c++ - 按字节读取文件

转载 作者:搜寻专家 更新时间:2023-10-31 01:20:04 32 4
gpt4 key购买 nike

我有一个简单的程序:

#include <cstring>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
cout << "Creating test.txt file..." << endl;

// Writing to file
fstream fWrite;
fWrite.open("./_test_data/test.txt", fstream::out | fstream::trunc);
if (fWrite.fail()) {
cout << "Creating test.txt file failed!" << endl;
fWrite.close();
} else {
fWrite << (char) 0x09 << (char) 0x0A << (char) 0x0B;
fWrite << (char) 0x0C << (char) 0x0D << (char) 0x0E;
fWrite << flush;

fWrite.close();
cout << "test.txt file successfully created." << endl;
}

// Reading created file
cout << "Reading test.txt file..." << endl;
fstream fRead;
fRead.open("./_test_data/test.txt", fstream::in);
if (fRead.fail()) {
fRead.close();
} else {
char character;

while (true) {
fRead >> character;

if (fRead.eof()) {
cout << (int)character << endl;
cout << "EOF detected!" << endl;
break;
}

cout << (int)character << endl;
}
fRead.close();
}

return 0;
}

它应该只按照 09 0A 0B 0C 0D 0E 的顺序写入字节,这样做没问题(通过 hexdump 检查),但是当读取同一个文件时,它读取第一个字节为 0E (= 十进制的 14)然后是 EOF...

Creating test.txt file...
test.txt file successfully created.
Reading test.txt file...
14
14
EOF detected!

为什么?

最佳答案

使用 fRead.read(&character,1)而不是 fRead >> character .

但您也可以删除 cout << (int)character << endl;在 if 语句中。

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

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