linux文件操作的一些函数

本文介绍了使用 dup、dup2 和 unlink 系统调用来复制文件描述符及删除文件的方法。dup 会在可用的最低编号中创建文件描述符的副本,而 dup2 则会关闭并替换指定的文件描述符。unlink 用于从文件系统中删除文件名及其指向的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dup, dup2, dup3 - duplicate a file descriptor

these system calls create a copy of the file descriptor oldfd.

dup() uses the lowest-numbered unused descriptor for the new descriptor.

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary, but note the following:

*
If oldfd is not a valid file descriptor, then the call fails, and newfd is not closed.
*
If oldfd is a valid file descriptor, and newfd has the same value as oldfd, then dup2() does nothing, and returns newfd.

#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
int main(int argc ,char *argv[])
{
        int fd=open("./1.c",O_RDONLY);
        printf("original fd is %d\n",fd);
        int new_fd=dup(fd);
        printf("new fd is %d\n",new_fd);

}

— Macro: int O_ACCMODE

This macro stands for a mask that can be bitwise-ANDed with the file status flag value to produce a value representing the file access mode. The mode will be O_RDONLYO_WRONLY, or O_RDWR. (On GNU/Hurd systems it could also be zero, and it never includes the O_EXEC bit.)


unlink - delete a name and possibly the file it refers to

unlink() deletes a name from the file system. If that name was the last link to a file and no processes have the file open the file is deleted and the space it was using is made available for reuse.


#include<fcntl.h>
#include<stdio.h>
int main(void)
{
        if(open("cc",O_RDWR)<0)
            printf("open error\n");
        if(unlink("cc")<0)
            printf("unlink error\n");
        printf("file unlinked\n");
        sleep(15);
        printf("done\n");
        exit(0);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值