c++ - fstream -> seekp()/tellp() 将不起作用

标签 c++ fstream

每当我想将位置设置为 X tellp return -1 时,fstream 中的 seekp() 有一个小问题。

代码:

fstream file("Riot.exe", ios::in | ios::binary | ios::out);
file.seekg(0, ios::beg);

...

if (...)
{ 
    long pos;
    file.seekp(882444);
    pos = file.tellp();
    std::cout << pos << std::endl; // pos = -1 
}

结果是pos返回-1,怎么办?

提前致谢!

最佳答案

要查找到文件末尾,将相对位置设置为 0,将基位置设置为 ios::end:

if (...)
{ 
    std::streampos pos;
    file.seekp(0, ios::end);                                                   /*
              ^^^^^^^^^^^^^                                                    */
    pos = file.tellp();
    std::cout << pos << std::endl; 
}

关于c++ - fstream -> seekp()/tellp() 将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17261211/

相关文章:

c++ - 为什么当我在 Ubuntu 终端上发送 SIGTERM (Ctrl + C) 时我的 C++ 代码没有终止?

c++ - 从文本文件中解析和拆分

c++ - reinterpret_cast 和 C 风格的转换有什么区别?

c++ - 具有互斥锁的 Visual C++ 线程不阻塞

c++ - 将 SDL_TTF 文本渲染到 openGL 红色方 block 上而不是文本

c++ - Ofstream 写入太多字节

c++ - 有没有办法截断打开的文件流?

c++ - 如何创建不需要Vista/Win7用户安装Visual C++可再发行组件的Windows可执行文件?

c++ - 在 C++20 中不能使用 { } 初始化,但在 C++17 中

c++ - 非常基本的 C++ 错误