linux系统中:“一切皆文件”,在linux系统中一切都以文件的形式存在的。
文件的分类:
- 普通文件
d 目录文件
p 管道文件:用于进程间的通信
c 字符设备文件:以数据流的方式进行数据的交互的驱动,例如:键盘,鼠标,蓝牙耳机。。。。。
b 块设备文件:以1024对其 2048 ,4096 数据块的方式,传输的驱动设备.例如:U盘 ,硬盘, 光驱 。。。。
s 网络文件:用于网络通信
l 链接文件:相当于windos的快捷方式, 硬链接(别名),软链接(快捷方式)
Linux系统IO的作用是提供接口给用户去访问linux系统中的驱动设备与普通文件等,是linux系统特有的,该IO接口是不带缓存的!!!
linux的系统IO的使用:
1 可执行程序或 shell 命令
2 系统调用(内核提供的函数)
3 库调用(程序库中的函数)
查看open函数的使用:
man 2 open
作用: 用来 打开 或 创建 一个 文件或设备
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
参数一:文件的路径名
参数二:权限与 附件功能
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写 (互斥的只能选择一个)
附加参数:
O_CREAT 文件不存在则创建新的 ****
O_EXCL 在创建文件的时候检查文件是否存在 **
O_TRUNC 在文件存在的时候,清空文件
O_APPEND 以追加的方式打开文件
O_LARGEFILE 打开大文件的时候需要 (32位2G以上) (64位4G以上)
返回值:成功 一个新的文件描述符
失败 -1
int open(const char *pathname, int flags, mode_t mode); 创建并打开
参数三:创建出来的文件权限 -rw-rw-rw-
int creat(const char *pathname, mode_t mode);
参数二:文件权限
注意:一个进程中,最多只能打开1024个文件,所以我们操作完一个文件后记得要把它关闭。
perror - print a system error message
#include <stdio.h>
void perror(const char *s);
参数一:错误前的自定义提示:字符串即可
#include <unistd.h>
int close(int fd);
--------------------------------------------
write:在一个文件描述符上执行写操作
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数一:需要写入的文件描述符
参数二:需要写入的数据缓存区
参数三:需要写入的数据大小
返回值:成功 返回写入的数据大小
失败 -1 并设置 错误号
注意:使用write函数的时候,必须要根据实际数据的大小填写count,不然会写入一些乱码到文件中。
read:在文件描述符上执行读操作
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数一:需要读取的文件描述符
参数二:数据的缓存区(用来保存读取后的数据)
参数三: 需要读取的数据大小
返回值:成功 返回读到的字节数
0 读到文件末尾
-1 失败
注意:使用read函数的时候,必须要大于实际数据长度,这样才能把所有数据读出来。因为read函数,他会返回0告诉用户文件已经读完了。
调整文件光标的位置:
lseek - reposition read/write file offset
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数一:文件描述符
参数二:偏移量
参数三:(参照物) SEEK_SET 文件头
SEEK_CUR 文件当前位置
SEEK_END 文件末尾
返回值:成功 文件偏移量
失败 -1
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int fd = open("1.c",O_RDWR);
if(fd < 0)
{
perror("open fail\n");
return -1;
}
char buf[1024]={0};
int ret = 0;
while(1)
{
memset(buf, 0, sizeof(buf));
ret=read(fd,buf,1024);
if(ret < 0)
{
printf("读取失败\n");
}
else if(ret == 0)
{
printf("已经读到文件末尾\n");
return 1;
}
else if(ret > 0)
{
printf("ret = %d\n", ret);
}
}
close(fd);
}