C++ read(),write() ,seekg(),tellg()

20 篇文章 0 订阅
istream &seekg(streamoff offset,seek_dir origin);
pos_type  tellg() 返回流置针所在的位置,返回值为整数
从文件origin位置开始移动offset个字节

读写数据块
  要读写二进制数据块,使用成员函数read()和write()成员函数,它们原型如下:

    read(unsigned char *buf,int num);
              write(const unsigned char *buf,int num);

read()从文件中读取 num 个字符到 buf 指向的缓存中,如果在还未读入 num 个字符时就到了文件尾,可以用成员函数 int gcount()来取得实际读取的字符数;而 write() 从buf 指向的缓存写 num 个字符到文件中,值得注意的是缓存的类型是 unsigned char *,有时可能需要类型转换。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中实现大文件的分段读写可以通过以下骤进行: 1. 打开文件:使用C++的文件流对象,如`std::ifstream`和`std::ofstream`,打开需要读取或写入的文件。 2. 确定文件大小:可以使用文件流对象的`seekg`和`tellg`函数来确定文件的大小。`seekg`函数用于将文件指针移动到指定位置,`tellg`函数用于获取当前文件指针的位置。 3. 分段读取:根据需要设置每次读取的分段大小,可以使用`read`函数从文件中读取指定大小的数据块。读取的数据可以存储在缓冲区中供后续处理。 4. 分段写入:根据需要设置每次写入的分段大小,可以使用`write`函数将数据块写入文件中。写入的数据可以从缓冲区中获取。 5. 关闭文件:在读取或写入完成后,使用文件流对象的`close`函数关闭文件。 下面是一个示例代码,演示了如何实现大文件的分段读写: ```cpp #include <iostream> #include <fstream> void splitFile(const std::string& inputFile, const std::string& outputFile, int segmentSize) { std::ifstream inFile(inputFile, std::ios::binary); std::ofstream outFile(outputFile, std::ios::binary); if (!inFile || !outFile) { std::cout << "Failed to open file!" << std::endl; return; } // 获取文件大小 inFile.seekg(0, std::ios::end); std::streampos fileSize = inFile.tellg(); inFile.seekg(0, std::ios::beg); // 分段读取和写入 char* buffer = new char[segmentSize]; std::streampos bytesRead = 0; while (bytesRead < fileSize) { int bytesToRead = (fileSize - bytesRead < segmentSize) ? (fileSize - bytesRead) : segmentSize; inFile.read(buffer, bytesToRead); outFile.write(buffer, bytesToRead); bytesRead += bytesToRead; } delete[] buffer; inFile.close(); outFile.close(); std::cout << "File split successfully!" << std::endl; } int main() { std::string inputFile = "input.txt"; std::string outputFile = "output.txt"; int segmentSize = 1024; // 每次读取或写入的分段大小 splitFile(inputFile, outputFile, segmentSize); return 0; } ``` 请注意,以上示例代码仅演示了如何实现大文件的分段读写,并未处理异常情况和错误检查。在实际应用中,需要根据具体需求进行适当的错误处理和异常处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值