Unix 环境高级编程-----文件操作函数

1. open()   O_RONLY O_WONLY O_RDWR 打开时必须有这3个参数的一个且只能有一个

  返回值为 文件描述符fd

2. creat()   创建新文件,这个函数的产生是因为最开始open函数没有O_CREAT 功能,所以单独开发的该函数

:不是create,没有e

3. read()  读取fd对应的文件内容

4. write() 写信息到fd对应的文件中

5. lseek()  设置当前文件偏移量 SEEK_SET, SEEK_CUR, SEEK_END

    返回值判断: ret == -1 不可以判断是否<0, 因为某些设备上偏移量可能为负,比如Intel X86 上的FreeBSD对应的/dev/kmem设备支持负偏移量

:lseek()只是将当前的偏移量记录在内核中,并不引起I/O操作。

6. close()  关闭fd对应的描述符

7.dup(fd)  复制文件描述符, 返回值为系统当前可用的文件描述符最小值

   dup2(fd, newFd)  复制fd为newFd, 当newFd已经被使用时,会先被关掉,然后复制为fd,当fd == newFd,直接返回fd; 

8. sync()  写缓存到磁盘;

    fsync()  写指定文件缓存到磁盘

    fdatasync() 只写文件的数据部分到磁盘,fsync在写磁盘时会同步更新文件的属性信息

9. fcntl()  更改已打开文件性质函数;

    参数F_DUPFD  fcntl(fd, F_DUPFD, int arg3) 返回系统中可用的>= arg3 中文件描述符的最小值。

    dup(fd)  <==> fcntl(fd, F_DUPFD, 0)

    dup2(fd, newFd)

    等效于: close(newFd); fcntl(fd, F_DUPFD, newFd); 但是并不相等;

    因为dup2是一个原子操作,而close, fcntl之间可能因为执行信号捕获函数改变文件描述符

小结: open() 的O_APPEND 可以提供原子操作,保证写入动作都是在文件尾,所以当文件open 时设置了O_APPEND,即使使用lseek 设置偏移量后写入信息,信息仍然会被写入文件尾!

 示例:

 1 #include <unistd.h>
 2 #include <fcntl.h>
 3 #include <stdio.h>
 4 #define BUF_MAX 4096
 5 
 6 int main()
 7 {
 8     int fd;
 9     fd = open("test.txt", O_RDWR | O_APPEND);
10     if (fd < 0)
11     {
12         printf("open test.txt failed\n");
13         return -1;
14     }
15     //设置当前文件偏移量为文件头;
16     lseek(fd,0, SEEK_SET);
17     char buf[BUF_MAX];
18     int len = read(fd, buf, 5);
19     if (len < 0)
20     {
21         printf("read test.txt failed\n");
22         return -1;
23     }
24     char msg[BUF_MAX];
25     printf("the 5 bytes read from test.txt head is:[%s]\n", buf);
26     lseek(fd, 0, SEEK_SET);
27     //写入len长度的字符串,buf 依然会被写入文件尾, lseek 无法影响写入逻辑,因为打开方式为O_APPEND
28     int ret = write(fd, buf, len);
29     if (ret != len)
30     {
31         printf("write info:[%s] to the end of test.txt failed\n", buf);
32         return -1;
33     }
34     printf("write info:[%s] to the end of test.txt succeed\n", buf);
35 
36 
37     close(fd);
38 
39     return 0;
40 }

make 文件:

test:test.c
    gcc test.c -o test
clean:
    rm -rf test

执行结果:

[xbh@bogon test]$ cat test.txt 
begin
end
[xbh@bogon test]$ ./test
the 5 bytes read from test.txt head is:[begin]
write info:[begin] to the end of test.txt succeed
[xbh@bogon test]$ cat test.txt 
begin
end
begin[xbh@bogon test]

在文件尾成功添加5个字符:begin

必须保证test.txt提前存在,否则会报open失败

转载于:https://www.cnblogs.com/xbh-blog/p/4304541.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值