如何截断文件从结尾? (跨平台) [英] How to truncate a file from the end? (cross platform)

查看:145
本文介绍了如何截断文件从结尾? (跨平台)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一个跨平台方法来从文件末尾删除 X 个字节。

I am trying to find a cross-platform method to delete X bytes from the end of a file.

目前我找到了:


  • 平台特定的解决方案(例如posix的truncate):这是我不要因为我想让C ++程序在多个平台上运行。

  • Platform specific solutions (such as truncate for posix) : This is what I don't want, because I want the C++ program to run on multiple platforms.

读取整个文件,再次写出文件减去我想要的字节删除:我想尽可能避免这种情况,因为我希望程序尽可能高效和快速。

Read in the whole file, and write out the file again minus the bytes I want to delete: I would like to avoid this as much as I can since I want the program to be as efficient and fast as possible

任何想法?

如果有一个转到文件流结束方法/函数,我可以后退X字节并剪切文件的剩余部分关闭或类似的东西?

If there is a "go to end of file stream" method/function, could I then rewind X bytes and cut the remainder of the file off or something similar?

推荐答案

只需创建自己的函数像这样:

How do you think cross platform functions work? Just make your own function like this:

int truncate(int fd, long size)
{
#ifdef _WIN32 || _WIN64 
    return _chsize(fd, size);
#else
  #ifdef POSIX
    return ftruncate(fd, size);
  #else
    // code for other OSes
  #endif
#endif
}

这篇关于如何截断文件从结尾? (跨平台)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆