Linux C 库中类似 SetFileLength() 的函数

发布于 2024-07-10 16:40:01 字数 100 浏览 2 评论 0原文

Linux下的C库中有没有可以设置文件长度的函数? 在Windows下我知道有一个SetFileLength()函数。 如果没有,在不删除和重写文件的情况下缩短文件的最佳方法是什么?

Is there a function in the C Library under Linux which can set the length of a file? Under Windows I know there is a SetFileLength() function.
If there is not, what is the best way of shortening a file without deleting and rewriting it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

枫以 2024-07-17 16:40:01

您可以使用截断功能

int truncate(const char *path, off_t length);

从手册页中:

“truncate() 和 ftruncate() 函数导致由路径命名或由 fd 引用的常规文件被截断为精确长度字节的大小。如果文件以前大于此大小,则额外的数据将丢失。如果文件以前较短,则扩展部分读取为空字节”。

You can use the truncate function.

int truncate(const char *path, off_t length);

From the man page:

"The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes. If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes"

携余温的黄昏 2024-07-17 16:40:01
   #include <unistd.h>
   #include <sys/types.h>

   int truncate(const char *path, off_t length);
   int ftruncate(int fd, off_t length);

从它的联机帮助页来看:

truncate() 和 ftruncate()
函数会导致名为的常规文件
通过路径或由 fd 引用
精确截断为大小
长度字节。

如果文件之前较大
超过这个大小,额外的数据是
丢失的。 如果该文件以前是
更短,它被延长,并且
扩展部分读取为空字节
('\0')。

   #include <unistd.h>
   #include <sys/types.h>

   int truncate(const char *path, off_t length);
   int ftruncate(int fd, off_t length);

From its manpage:

The truncate() and ftruncate()
functions cause the regular file named
by path or referenced by fd to be
truncated to a size of precisely
length bytes.

If the file previously was larger
than this size, the extra data is
lost. If the file previously was
shorter, it is extended, and the
extended part reads as null bytes
('\0').

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文