截断或调整文件大小以修改其结尾

截断或调整文件大小以修改其结尾

本文介绍了截断或调整文件大小以修改其结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 FILE *文件,它包含一些二进制数据。让我们说这个数据是一个双列表,最后一个条目是一个字符串,描述什么是双。我想修改这个字符串(新的字符串可能会更短)。所以首先我删除旧的字符串。我需要找到字符串的起点:

  fseek(file,-size(sring.size()),SEEK_END ); 

然后我应该怎么办?我发现链接,但我不知道使用哪个...一旦文件重新调整大小,我可以使用 fwrite

解决方案/ div>

如果您要调整文件大小,请 ftruncate()()是您要查找的功能。您需要在 FILE * 结构上调用 fileno(),以获取 ftruncate()



一旦文件大小缩小后,添加新数据只是寻求到结束( fseek(file,0,SEEK_END))和 fwrite()



EDIT:请记住在截断文件之前调用 fflush()


I have a FILE* file that holds some binary data. Let's say that this data are a list of double and that the last entry is a string that describes what are those double. I want to modify this string (the new string might be shorter). So first i delete the old string. I need to find the starting point of the string :

fseek(file,-size(sring.size()),SEEK_END);

and then what should i do ? i found Delete End of File link but i don't know which one to use... Once the file is re-sized, can i simply write my new string using fwrite ?

解决方案

If you want to resize a file, then ftruncate() (http://www.linuxmanpages.com/man2/ftruncate.2.php) is the function you're looking for. You'll need to call fileno() on the FILE * structure to get the file descriptor for ftruncate(), though.

As for appending the new data (the new string) once the file has been reduced in size, just seeking to the end (fseek(file, 0, SEEK_END)) and fwrite()'ing there should do it.

EDIT: remember to call fflush() before truncating the file!

这篇关于截断或调整文件大小以修改其结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:46