C ++如何对象与给定的偏移读?
-
20-08-2019 - |
题
现在我有在它的许多数据的文件。 我知道在位置(长)X我需要的数据开始,有一个给定大小的sizeof(Y) 我怎样才能得到这些数据?
解决方案
使用seek
方法:
ifstream strm;
strm.open ( ... );
strm.seekg (x);
strm.read (buffer, y);
其他提示
您应该使用FSEEK()在文件中改变你的“当前位置”到期望的偏移。所以,如果“F”是你的FILE *变量,偏移补偿,这是调用应该怎么样子(我的模漏内存):
fseek(f, offset, SEEK_SET);
除了上述常用的寻找和阅读的技巧,你也可以在文件中使用类似的 MMAP()和直接访问数据。
例如,给出下面的数据文件 “foo.dat”:
one two three
下面的代码将打印使用 MMAP的前四个字节之后的所有文本()基础的方法:
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
int main()
{
int result = -1;
int const fd = open("foo.dat", O_RDONLY);
struct stat s;
if (fd != -1 && fstat(fd, &s) == 0)
{
void * const addr = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (addr != MAP_FAILED)
{
char const * const text = static_cast<char *>(addr);
// Print all text after the first 4 bytes.
std::cout << text + 4 << std::endl;
munmap(addr, s.st_size);
result = 0;
}
close(fd);
}
return result;
}
您甚至可以使用这种方法来直接写入文件(记得的msync()如有必要)。
像升压和ACE库为MMAP()(和等效视窗函数)提供很好的C ++封装。
这方法可能是对小文件矫枉过正,但它可以为大文件巨大的胜利。与往常一样,分析代码,以确定哪种方法是最好的。
不隶属于 StackOverflow