您的位置:首页 > 运维架构 > Linux

linux文件操作的一些函数

2012-12-31 21:21 561 查看
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_RDONLY
,
O_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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: