当前位置:实例文章 » 其他实例» [文章]文件IO_文件截断_ftruncate,truncate(附Linux-5.15.10内核源码分析)

文件IO_文件截断_ftruncate,truncate(附Linux-5.15.10内核源码分析)

发布人:shili8 发布时间:2025-02-07 00:21 阅读次数:0

**文件IO_文件截断_ftruncate,truncate**

在 Linux 中,`ftruncate()` 和 `truncate()` 是两个用于截断文件的系统调用。它们允许用户在打开一个文件后改变其大小。这一功能对于管理磁盘空间至关重要。

###1. ftruncate()

`ftruncate()` 是一个用于截断已打开文件的函数,它接受两个参数:文件描述符 `fd` 和新长度 `length`。如果成功,返回值为0;否则,返回 `-1`。

cint ftruncate(int fd, off_t length);


**示例代码**

c#include <stdio.h>
#include <fcntl.h>

int main() {
 int fd = open("test.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
 if (fd == -1) {
 perror("open");
 return1;
 }

 // 将文件长度设置为10 个字节 if (ftruncate(fd,10) !=0) {
 perror("ftruncate");
 close(fd);
 return1;
 }

 close(fd);

 return0;
}


在上面的示例中,我们首先使用 `open()` 函数打开一个名为 "test.txt" 的文件,并将其长度设置为10 个字节。

###2. truncate()

`truncate()` 是用于截断未打开的文件的函数,它接受两个参数:文件路径 `path` 和新长度 `length`。如果成功,返回值为0;否则,返回 `-1`。

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


**示例代码**

c#include <stdio.h>
#include <unistd.h>

int main() {
 // 将文件长度设置为10 个字节 if (truncate("test.txt",10) !=0) {
 perror("truncate");
 return1;
 }

 return0;
}


在上面的示例中,我们直接使用 `truncate()` 函数将 "test.txt" 文件的长度设置为10 个字节。

### Linux-5.15.10内核源码分析#### ftruncate()

`ftruncate()` 的实现位于 `fs/fcntl.c` 文件中:

cSYSCALL_DEFINE1(ftruncate, int, fd, unsigned long, length)
{
 struct file *file;
 loff_t new_size;

 if (fd < 0 || fd >= NR_OPEN_DEFAULT)
 return -EBADF;

 file = get_file(fd);
 if (!file)
 return -EBADF;

 new_size = (loff_t)length;

 if (file->f_op->ftruncate)
 return file->f_op->ftruncate(file, new_size);

 return -EIO;
}


在上面的代码中,我们首先检查文件描述符 `fd` 是否有效,然后获取对应的文件结构体 `file`。如果文件操作函数 `ftruncate()` 存在,则调用它;否则,返回 `-EIO`。

#### truncate()

`truncate()` 的实现位于 `fs/truncate.c` 文件中:

cSYSCALL_DEFINE2(truncate, const char __user *, path, unsigned long, length)
{
 struct dentry *dentry;
 int error;

 if (length < 0)
 return -EINVAL;

 dentry = lookup_dentry(path);
 if (!dentry)
 return -ENOENT;

 error = security_truncate(dentry, length);
 if (error)
 return error;

 error = generic_truncate(dentry, length);
 if (error)
 return error;

 return0;
}


在上面的代码中,我们首先检查新长度 `length` 是否有效,然后查找文件的 dentry 结构体。如果找到,则调用安全函数 `security_truncate()` 和通用函数 `generic_truncate()` 来截断文件。

综上所述,`ftruncate()` 和 `truncate()` 是两个用于截断文件的系统调用,它们允许用户在打开一个文件后改变其大小。它们的实现位于 Linux 内核源码中,并且提供了对磁盘空间管理的支持。

其他信息

其他资源

Top