一、open函数
可以使用man 2 查看open的使用方法,头文件等一些内容
1、opens所包含的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
2、open的格式
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
第一个参数:想要打开的文件名
第二个参数:打开的方式(只读,只写,读写。必须选一个,后面可以用”|“来添加其他的功能,例如加O_CREAT,文件不存在则创建)
第三个参数:在创建新的文件的时候,给文件设置权限,可以用八进制来设置
3、返回值:
成功:返回文件描述符(给文件编号,便于操作)
失败:返回-1
4、出错提示的两种方式:
errn0:错误的标号(要加头文件,可以用man查看)
perror:可以打印错误的信息。
5、注意:在共享文件夹中创建的文件是在windows下创建的,不能用第三个参数来改变权限
权限的设置:是mode(你写的) & (~umask)
文件描述符默认是当前可用的最小的文件描述符,但在打开文件的时候0,1,2默认打开了
不使用文件的时候要将文件关闭。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
//第一个参数是要打开的文件名\
二个参数是打开文件的方式(只读,只写,读写)可以用|添加其他条件\
第三个参数是创建新文件时,给新文件的权限(用8进制)
int fd1 = open("test", O_RDWR | O_CREAT,0755);
int fd2 = open("test", O_RDWR | O_CREAT,0755);
int fd3 = open("test", O_RDWR | O_CREAT,0755);
if(-1 == fd1 || -1 == fd2 ||-1 == fd3)
{
printf("%d\n",errno); //相应错误的编号
perror("文件test打开失败"); //打印出响应的错误
}
else
printf("打开文件test成功\n");
printf("%d\n",fd1);
printf("%d\n",fd2);
printf("%d\n",fd3);
close(fd1);
close(fd2);
printf("------------------------------------\n");
int fd4 = open("test", O_RDWR | O_CREAT,0755); //fd
if(-1 == fd4 )
{
perror("文件test打开失败");
}
printf("%d\n",fd1);
printf("%d\n",fd2);
printf("%d\n",fd3);
printf("%d\n",fd4);
close(fd3);
close(fd4);
return 0;
}
二、read函数
阻塞型:读的时候如果没有数据可以读,则等待到有数据可以读才会继续执行。(对于读来说,只有设备文件和网络文件才是阻塞型的,常规文件不会阻塞)
1、头文件
#include <unistd.h>
2、格式
ssize_t read(int fd, void *buf, size_t count);
第一个参数:读的文件的文件描述符
第二个参数:存放文件内容的地址
第三个参数:想要读的大小(字节)
3、返回值
成功:返回实际读到的字节数(可能和前面形参中的count不同)
4、注意:读文件的时候要先打开文件,最后记得关闭文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define SIZE 1024
//读大数据,确保数据读完
int main()
{
int fd = open("test1.c", O_RDONLY);
if(-1 == fd)
{
perror("打开文件test1.c失败");
return -1;
}
char buf[SIZE];
char *p =buf;
int count = SIZE;
while(count)
{
ssize_t ret = read(fd,p,count);
printf("%ld\n",ret);
if(-1 == ret)
{
perror("读文件test1.c失败");
return -1;
}
p += ret;
count -= ret;
}
buf[SIZE] = 0;
printf("%s\n",buf);
close(fd);
return 0;
}
int main2()
{
int fd = open("test1.c", O_RDONLY);
if(-1 == fd)
{
perror("打开文件test1.c失败");
return -1;
}
char buf[SIZE+1];
int ret = 0;
int count = 0;
while((ret = read(fd,buf,SIZE)) != 0)
{
if(-1 == ret)
{
perror("读文件test1.c失败");
return -1;
}
count++;
buf[ret] = '\0';
printf("%s",buf);
}
printf("count = %d\n",count);
close(fd);
return 0;
}