1.Linux应用编程---文件I/O(open、read、write、lseek、close)
2016-01-07 10:40
337 查看
文件描述符
定义:对内核而言,文件描述符相当于一个文件的标识,它是一个非负整数,当打开(open)一个现有文件或者创建(creat)一个新文件时,内核会向进程返回一个文件描述符在unix中(文件描述符 0–标准输入 1–标准输出 2–标准错误)
open
[code]#include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int open(const char *pathname, int oflag, .../*mode_t mode*/)
参数1:打开或者创建文件的名字
参数2:选项参数,可选择多个参数用 | 构成
其中: O_RDONLY 只读打开 O_WRONLY只写打开 O_RDWR读写打开只能选择一个
下面是可选择的
O_APPEND 每次都追加在文件的尾端
O_CREAT 若文件不存在,则创建它,使用此项,需要指定第三个参数mode,用于设定新文件的权限
O_EXCL 若指定了O_CREAT,而文件存在则会报错,用于测试一个文件是否存在,不存在则创建
O_TRUNC 如果此文件存在,而且为只写或读写成功打开,则将其长度截为0
参数3:…表示余下参数的数量和类型根据具体调用会有所不同,通常创建新文件时才使用表示权限
read
[code]#include <unistd.h> size_t read(int fd,void *buf,size_t nbytes)
描述:从文件描述符相关联的文件里读入nbytes个字节的数据,把它们放到数据区buf中,并返回读入的字节数
参数1:文件描述符
参数2:存放从文件中读取的数据的存储区
参数3:读出的字节数
返回值
0 未读入任何数据,已达文件尾
-1 表示出错
其它 读出的字节数
write
[code]#include <unistd.h> size_t write(int fd,const void *buf,size_t nbytes)
描述:把缓冲区buf前nbytes个字节写入文件描述符fd相关联的文件中,返回实际写入的字节数
参数1:文件描述符
参数2:写入文件的缓冲区指针
参数3:读出的字节数
返回值
0 未写入任何数据
-1 表示出错
其它 写入的字节数
lseek
[code]#include <unistd.h> off_t lseek(int fd,off_t offset,int whnece)
描述:移动文件指针到指定位置
参数1:文件描述符
参数2:偏移量,具体与第三个参数有关
参数3:SEEK_SET 文件头 SEEK_CUR 当前位置 SEEK_END 文件尾
close
[code]#include <unistd.h> int close(int fd)
描述:关闭一个打开的文件
参数1:文件描述符
返回值
小于0 关闭失败
其它 关闭成功
下面根据上述写一个综合案例
[code]#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { int fd,size; char* buf = "hello,I'm wxp,this is my job!"; char buf_r[20]; int len = strlen(buf);//数组长度 printf("len = %d\n",len); /*调用open创建wxp.c*/ if((fd = open("./wxp.c",O_CREAT|O_TRUNC|O_RDWR,0666)) < 0) { printf("open fail\n"); exit(1); } else { printf("open file: wxp.c fd = %d\n",fd); } /*write写入*/ if((size = write(fd,buf,len)) < 0) { printf("write fail\n"); exit(1); } else { printf("write: %s\n",buf); printf("write size = %d\n",size); } /*lseek函数移动文件指针位置到文件开头*/ lseek(fd,0,SEEK_SET); if((size = read(fd,buf_r,15)) < 0) { printf("read fail\n"); exit(1); } else { buf_r[15] = '\0'; printf("read from wxp.c the content is %s\n",buf_r); printf("read size = %d\n",size); } if(close(fd) < 0) { printf("close fail\n"); exit(1); } else { printf("close wxp.c\n"); } return 0; }
运行结果如下:
相关文章推荐
- linux下符号链接和硬链接的区别
- Centos6.5 VNC 配置
- CentOS7 卸载KDE桌面
- CentOS7下LVS+Keepalived实现高性能高可用负载均衡
- Linux系统中列出PCI设备和USB设备的命令详解
- Linux 日常高频操作整理
- Centos 6.2 32位安装zabbix
- Linux下Java环境变量配置
- linux进程间通信-----信号总结
- linux分区基础和基础优化
- Linux 的虚拟文件系统--各结构之间的联系
- CentOS 6.4下编译安装MySQL 5.6.14
- 【Linux高频命令专题(23)】tar
- Linux下Bond网卡配置
- Linux 命令行界面->GUI界面
- linux 下监控某个进程的资源占用
- centos7下的lnmp环境安装
- [王垠系列]谈 Linux,Windows 和 Mac
- Linux下安装svn服务器
- Centos文件系统创建浅析