gpt4 book ai didi

c++ - 从二进制文件读取字节到 long int

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:05:10 44 4
gpt4 key购买 nike

我有两个问题:

  • 我有一个二进制文件中的数据。我想通过使用读取函数读取前 8 个字节以签名 long int,但我不能。你知道我该怎么做吗?

  • 如何直接读取一段数据为字符串?我可以像中所示那样阅读吗例如:

     ifstream is;
    is.open ("test.txt", ios::binary );

    string str ;
    is. read ( str.c_str, 40 ) ; // 40 bytes should be read

最佳答案

I want read first 8 bytes to signed long int by using read function but I could not . Do you know how can I do that?

不要假设 long 足够宽,通常情况下并非如此。 long long 保证至少有 8 个字节宽,但是:

long long x;
is.read(static_cast<char *>(&x), 8);

请注意,由于整数大小和字节顺序不同,这仍然非常不可移植。

关于你的第二个问题,试试

char buf[41];
is.read(buf, 40);
// check for errors
buf[40] = '\0';

std::string str(buf);

或者,更安全

char buf[41];
is.get(buf, sizeof(buf), '\0');
std::string str(buf);

关于c++ - 从二进制文件读取字节到 long int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8019844/

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