2017-04-16 52 views
2

我目前正在编写一个文件页面管理程序,它基本上是将二进制文件写入,追加和读取页面。对于写作功能,我必须删除指定页面的全部内容并写入新内容。我需要删除特定范围内的文件中的数据,例如将数据从位置30删除到位置4096.如何根据偏移量从文件中删除数据?

回答

0

删除文件中的数据的唯一方法是将其标记为已删除。使用某个值来表示该部分被删除。否则,将要保存的部分复制到新文件中。

+0

我可以使用什么样的性格来表示一个字符已被删除或从这一点也没有更多的数据看? – daniel

1

如果位置4096之后没有更多数据,则可以使用truncate(2)将文件缩小为30个字节。

如果4096字节后有更多的数据,那么你可以首先用第4096字节后出现的数据覆盖从位置30开始的数据。然后你可以将文件截断为[original_filesize - (4096-30)]个字节。

0

那么容易std::string

以下步骤:
读取该文件,并将其解压到的std :: string

std::ifstream input_file_stream("file"); 
const unsigned size_of_file = input_file_stream.seekg(0, std::ios_base::end).tellg(); 

input_file_stream.seekg(0, std::ios_base::beg); // rewind 

std::string whole_file(size_of_file, ' ');  // reserved space for the whole file 

input_file_stream.read(&* whole_file.begin(), size_of_file); 

然后删除你想要什么:

// delete with offset 
whole_file.erase(10,  // size_type index 
       200);  // size_type count 

并最终写入新文件:

// write it to the new file: 
std::ofstream output_file_stream("new_file"); 
output_file_stream.write(&*whole_file.begin(), whole_file.size()); 
output_file_stream.close(); 

input_file_stream.close();