#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#define SIZE 1024
/*
open()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags, mode_tmode);
pathname:要打开或要创建的文件名称
flags:标志位,指定打开文件的操作方式
mode:指定新文件的访问权限(仅当创建新文件时才用)
返回值:若成功返回fp(文件描述符),否则返回-1
*/
int main1()
{
//close(1);
//打开一个文件
int fd = open("open.c",O_RDWR | O_CREAT,077);
if(fd == -1)
{
printf("creat fail\n");
perror("open ");
printf("%s\n",strerror(errno));
}
printf("fd = %d\n",fd);
//close(fd);
return 0;
}
/*
read()
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
fd:要读取的文件的描述符。
buf:读取到的数据要放入的缓冲区。
count:要读取的字节数。
返回值:若成功返回读到的字节数,若已到文件结尾则返回0,若出错则返回-1并设置变量errno的值。
注意:
1. 这里的size_t是无符号整型,ssize_t是有符号整型。
2. buf指向的内存空间必须事先分配好。
*/
int main2()
{
char buf[SIZE] = {0};
int fd = open("sqstack.c",O_RDWR ,077);
if(fd == -1)
{
printf("creat fail\n");
perror("open ");
printf("%s\n",strerror(errno));
}
ssize_t ret = read(fd,buf,SIZE-1);
if(ret == -1)//出错则返回-1
{
perror("read ");
}
if(ret == 0)//若已到文件结尾则返回0,成功返回读到的字节数,
{
printf("read over\n");
}
printf("buf len = %d\n",strlen(buf));//文件字节数
printf("读到第%d个字节: %s \n",ret,buf);
return 0;
}
//缓冲区问题
/*
read每次读的数据是调用者要求的大小,
比如调用要求读取10个字节数据,read就会读10个字节数
据到数组中,而fread不一样,为了加快读的速度,
fread每次都会读比要求更多的数据,然后放到缓冲区中,
这样下次再读数据只需要到缓冲区中去取就可以了。
*/
int main3()
{
#if 0
int fd = open("sqstack.c",O_RDONLY ,0777);
if(fd == -1)
{
printf("creat fail\n");
perror("open ");
printf("%s\n",strerror(errno));
}
char buf[SIZE] = {0};
while(1)
{
//1 memset(buf,0,SIZE);//读完数据之前清空缓存区
ssize_t ret = read(fd,buf,SIZE-1);
if(ret == -1)//出错则返回-1
{
perror("read ");
}
if(ret == 0)//若已到文件结尾则返回0,成功返回读到的字节数,
{
printf("read over\n");
break;
}
//2 buf[ret] = '\0';//每次读完之后将末尾字节置为'\0'
printf("%s\n",buf);
}
#endif
//读取一个完整的数据
int fd = open("sqstack.c",O_RDONLY ,0777);
if(fd == -1)
{
printf("creat fail\n");
perror("open ");
printf("%s\n",strerror(errno));
}
char buf[SIZE] = {0};
char *p = buf;
int count = SIZE - 1;//每次要读的数据个数
ssize_t ret = 0;
while(ret = read (fd, p, count))
{
if(ret == -1)//出错
{
//EINTR 在读取到数据以前调用被信号所中断.
//EAGAIN 使用O_NONBLOCK 标志指定了非阻塞式输入输出,但当前没有数据可读.
if(errno == EAGAIN || errno == EINTR)
{
continue;
}
break;
}
if(ret == 0)//读完数据
{
break;
}
count -= ret;//下一次要都的数据
p += ret;
}
printf("len = %d\n",strlen(buf));
printf("%s\n",buf);
return 0;
}
文件操作的系统调用之open,read
最新推荐文章于 2025-02-11 16:47:17 发布