open
查看man 2 open
int open(const char* pathname,int flags);
int open(const char* pathname,int flags,mode_t mode);
pathname文件名
flags必选项 O_RDONLY只读 O_WRONLY只写 O_RDWR读写
可选项 O_APPEND追加
O_CREAT创建文件
O_EXCL与O_CREAT一起使用,如果文件存在则报错
mode权限位,最终(mode&~umask)
O_NONBLOCK非阻塞
返回值:返回最小的可用文件描述符,失败返回-1,设置errno
close
int close(int fd);
fd open打开的文件描述符
返回值:成功返回0,失败返回-1,设置errno
mytouch.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
if(argc!=2){
print("./a.out filename\n");
return -1;
}
int fd=open(argv[1],O_RDONLY|O_CREAT,0666);
close(fd);
return 0;
}
read读
ssize_t read(int fd,void *buf,size_t count)
fd文件描述符
buf缓冲区
count缓冲区大小
返回值:
成功返回读到的大小
失败返回-1,设置errno
0代表读到文件末尾
非阻塞的情况下返回-1,但是此时需要判断errno的值
write写
ssize_t write(int fd,void *buf,size_t count)
fd文件描述符
buf缓冲区
count缓冲区大小
返回值:
成功返回写入的字节数
失败返回-1,设置errno
0代表未写入
实现一个cat功能:读文件,输出到屏幕
mycat.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
if(argc!=2){
print("./a.out filename\n");
return -1;
}
int fd=open(argv[1],O_RDONLY);
//读,输出到屏幕
char buf[256];
int ret=read(fd,buf,sizeof(buf));
write(STDOUT_FILENO,buf,ret);
//TODO:循环读取,读到0结束
close(fd);
return 0;
}
需求:打开一个文件,写入内容helloworld,读取文件内容输出到屏幕
myreadwrite.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
if(argc!=2){
print("./a.out filename\n");
return -1;
}
int fd=open(argv[1],O_RDWR|O_CREAT,0666);
write(fd,"helloworld",11);
lseek(fd,0,SEEK_SET);
char buf[256]={0};
int ret=read(fd.buf,sizeof(buf));
if(ret){
write(STDOUT_FILENO,buf,ret);//STDIN_FILENO,STDERR_FILENO
}
close(fd);
return 0;
}
lseek移动文件读写位置
off_t lseek(int fd,off_t offset,int whence)
fd 文件描述符
offset偏移量
whence SEEK_SET文件开始位置 SEEK_CUR当前位置 SEEK_END结尾
返回值 成功:返回当前位置到开始的长度,失败:返回-1,设置errno
lseek的作用:
移动文件读写位置
计算文件大小
拓展文件
filesize.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
if(argc!=2){
print("./a.out filename\n");
return -1;
}
//1.open
int fd=open(argv[1],O_RDONLY);
//2.lseek,得到返回值
int ret =lseek(fd,0,SEEK_END);
printf("file size is %d\n",ret);
//3.close
close(fd);
return 0;
}
filecreate.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
if(argc!=2){
print("./a.out filename\n");
return -1;
}
//1.open
int fd=open(argv[1],O_WRONLY|O_CREAT,0666);
//2.lseek,拓展文件
int ret =lseek(fd,1024,SEEK_END);
//需要至少写一次,否则不能保存
write(fa,"a",1);
//3.close
close(fd);
return 0;
}
本文介绍了如何使用C语言API实现cat功能,即读取文件内容并输出到屏幕,并展示了如何通过open(), write(), lseek()等函数来写入'helloworld'到指定文件中。
5504

被折叠的 条评论
为什么被折叠?



