UNIX File IO

14 篇文章 0 订阅

多数Unix I/O常用的5个系统调用有functions:open,read,write,lseek and close,它们一般被称为无缓冲的I/O

无缓冲意味着每一次read, write文件都直接调用了内核的系统调用

open函数的三个参数:

(1)path是已经存在的文件的路径;

(2)oflags参数:若值为 O_RDONLY ,就以只读方式打开文件;

               若值为 O_WDONLY,就以只写方式打开文件;

               若值为 O_RDWR,就以读写方式打开文件;

(3)参数mode:文件的权限,对于一个已经存在的文件,参数mode是没有用的,通常将其省略,因此这种情况下open调用只需两个参数。

这篇博客把open read write 和close 的用法写得很详细

https://blog.csdn.net/MOON5555/article/details/78411514

一个write()写入文件的小例子

(我第一次写的时候报了错,因为我把O_WRONLY写成0_WRONLY,前面是大写字母O而不是数字0)

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main(){
int fd=open("./file.txt",O_WRONLY|O_CREAT);
printf("fd=%d\n",fd);
write(fd,"hellohi",7);
close(fd);
}

一个read()读出文件的小例子

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main()
{
int fd=open("file.txt",O_RDONLY);
printf("fd=%d\n",fd);
char buff[128];
read(fd,buff,127);
printf("read:%s\n",buff);
close(fd);

}

文件描述符:0    标准输入流

                     1    标准输出流

                     2    标准错误流

#include <unistd.h>
#include <stdio.h>
#define BUFSIZ 4096

int main()
{
	char buf[BUFSIZ];
	int numread;
	while((numread = read(0, buf, sizeof(buf))) > 0)
		write(1, buf, numread);
	exit(0);
}

关于lseek,这篇博客写得很详细

https://www.jianshu.com/p/6b4adc33d9a9

其他可供参考的博客

https://blog.csdn.net/u011068702/article/details/54176227

https://blog.csdn.net/songyulong8888/article/details/78632289

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值