比如我有一个文件test.dat
,它的大小是512KB(固定值),我想从第32KB的位置开始读取32KB的数据,该怎么实现?
多谢!
linux下也可使用mmap,将文件映射到内存到中,直接操作指针加到32KB位置;
mmap()函数中有个offset参数,就是文件映射的起始位置,传入32KB,内存操作的指针首地址就是从32KB开始;
int fd=open("/path/to/your/test.dat", O_RDONLY);
void *p=mmap(NULL, 32768, PROT_READ, MAP_PRIVATE, fd, 32768);
然后你就可以使用指针p
指向的32K内存了,里面就是你要的文件里的内容。
用完之后用munmap(p, 32768)
释放资源,然后用close(fd)
关闭文件。
标准库里面提供了你需要的功能,下面这个例子用的是stringstring,ifstream也是一样的,他们都是继承自basic_istream,更多信息可以看这个链接:std::basic_istream::seekg
c
#include <iostream> #include <string> #include <sstream> int main() { std::string str = "Hello, world"; std::istringstream in(str); std::string word1, word2; in >> word1; in.seekg(0); // rewind in >> word2; std::cout << "word1 = " << word1 << '\n' << "word2 = " << word2 << '\n'; } // Output: // word1 = Hello, // word2 = Hello,
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答3.3k 阅读
ifstream
可以移动文件指针。