文件IO学习笔记之一

I文件IO ===》操作系统对外封装的一组用户使用的系统调用
接口函数。
帮助手册使用 man 2 xxx

文件io ===》描述符 文件系统 io函数

文件系统: 非缓存文件系统,在所有IO操作的过程中没有
缓存区的存在。

描述符: 相对与标准io的文件操作对象,
标准io : FILE * 文件流指针
文件io : int 文件描述符
文件描述符特征: 最小 未用 非负 整数

最小: 默认从3 开始,0 == STDIN_FILENO
1 == STDOUT_FILENO
2 == STDERR_FILENO

   注意区别: 标准io的 stdin  stdout stderr

未用: 如果有文件描述符释放,则系统自动回收,并
在系统下次打开文件的时候再次使用。

非负整数: >= 0 整数。

文件io操作框架:
文件打开 ===》文件读写(文件定位) ===》文件关闭
open() read()/write()/lseek close()

打开操作:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int open(const char *pathname, int flags);
功能:该函数可以指定方式打开指定路径+名称的文件。
参数: pathname 要打开的文件路径+名称
flags 打开文件方式:
O_RDONLY 只读
O_WRONLY 只写
O_RDWR 读写
要求文件必须存在。
返回值: 成功 返回文件描述符
失败 -1

一个进程中最多能同时打开 1024 个文件 《===ulimit -a

关闭操作:
#include <unistd.h> === POSIX 标准

int close(int fd);
功能:用来关闭指定的文件描述符
参数:fd 要关闭的文件描述符,可以关多次。
返回值:成功 0
失败 -1;

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	int fd = open("./abc",O_RDONLY);
	if(fd < 0)
	{
		perror("open error");
		return -1;
	}
	printf("open fd = %d \n",fd);


	close(fd);
    return 0;
}

文件IO操作:
#include <unistd.h>

ssize_t read(int fd, void *buf, size_t count);
功能:通过该函数可以从fd指定的文件中获取长度为
count字节的数据到buf所在的本地内存。
参数:fd 要读数据的文件描述符。
buf 用来存储读到的数据。
count 控制读的数据长度,单位字节。
返回值:成功 返回获取到的数据长度,一般小于等于count
失败 -1
文件结尾 0

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	int fd = open("./abc",O_RDONLY);
	if(fd < 0)
	{
		perror("open error");
		return -1;
	}
	printf("open fd = %d \n",fd);

	while(1)
	{
		char buff[128] ={0};
		int ret = read(fd,buff,sizeof(buff)-1);
		if(ret < 0)
		{
			perror("read error");
		}
		else if(ret == 0)
		{
			break;
		}
		else
		{
			printf("%s",buff);
		}
	}
	close(fd);
    return 0;
}

ssize_t write(int fd, const void *buf, size_t count);
功能:向指定的fd文件中写入长度为count字节的数据。
参数:fd 文件描述符
buf 要写入文件的信息。
count 要写入文件的数据长度,单位字节。
返回值:成功 返回写入的数据长度
失败 -1

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
	int fd = open("./abc",O_WRONLY);
	if(fd < 0)
	{
		perror("open error");
		return -1;
	}

	//write(fd,"hello world",11);
	char buff[128] ={0};
	printf("input str\n");
	int ret = read(STDIN_FILENO,buff,sizeof(buff));
	write(fd,buff,ret);

	close(fd);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值