Linux 环境编程之文件I/O:文件读写

函数接口

#include<unistd.h>
ssize_t read(int fd, void *buf, size_t nbytes);
ssize_t write(int fd, const void *buf, size_t nbytes);

read使用:

  • read成功,返回实际读取到的字节数(可能小于指定的),失败返回-1;
  • 读普通文件时,若已到达文件尾端,则返回0;
  • 读终端设备时,通常一次最多读一行
  • 从网络读取时,网络的缓冲机制可能使返回值小于要求读取字节数。
  • 从管道或FIFO读时,若管道包含字节数小于所要求读取的,read只返回可读的字节数

write使用:

  • 返回值通常与参数nbytes相同,否则表示出错。出错原因之一是磁盘满了,或超出给定进程文件长度限制
  • 普通文件的写从文件起始处开始,O_APPEND则从文件末尾开始,写成功则偏移量增加写入的字节数。

测试代码:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>

//#define rw

int main()
{
    #ifdef rw
	    int fd = open("readwrite.txt", O_RDWR |O_CREAT, 0600);
	#else
	    int fd = open("readwrite.txt", O_WRONLY |O_CREAT, 0600);
	#endif
	if (fd < 0)
	{
		printf("open file error\n");
		return -1;
	}

	// write
	char buf[64];
	snprintf(buf, sizeof(buf), "hello world.");
	printf("buf:%s\n", buf);
	if (write(fd, buf, strlen(buf)) != strlen(buf))
	{
		printf("write file error\n");
		close(fd);
		return -1;
	}
	int pos = lseek(fd, 0, SEEK_CUR);
	printf("curr pos:%d\n", pos);
    #ifndef rw
	    close(fd);
    #endif

	pos = lseek(fd, 0, SEEK_CUR);
	printf("curr pos:%d\n", pos);

	// read
    #ifndef rw
	    fd = open("readwrite.txt", O_RDONLY |O_CREAT);
	#endif
	char rdbuf[64];
	int len = sizeof(rdbuf);
	while(len > 0)
	{
		int rdbytes = read(fd, rdbuf + sizeof(rdbuf) - len, len);
		if (rdbytes <= 0)
			break;
		len -= rdbytes;
	};
	printf("read:%s\n", rdbuf);
	pos = lseek(fd, 0, SEEK_CUR);
	printf("curr pos:%d\n", pos);
	close(fd);

}

如果以读写方式打开,读写共用一个偏移量,可以对 #define rw 注释或解注释看看。

 

参考:

Linux C API 参考手册

LinuxAPI

《Unix环境高级编程》3.7-3.8小节

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值