linux 文件i/o编程小结

借用别人的一句话:
说到文件 IO 编程,那当然首先要来谈一谈在 Linux 操作系统里,什么是文
件?记得以前说过,在 Linux 中,几乎一切都可以看做是文件。串口、打印机、
硬盘等设备都可以看做是文件,学过驱动的应该都知道/dev/xxx 都是设备文件。
大多数情况下,这些文件都会涉及的函数接口一般有以下 5 个,open,
read,write,ioctl,close。有人也许会说,目录也是文件吗?没错,目录在 Linux 环
境下确实是一个文件,只不过打开目录文件,用的函数不再是 open/read 而是
opendir/readdir 接口来读取目录。另外,应用程序工程师不必了解上面提到的系
统接口函数是如何实现的。总结一下:Linux 中的文件主要分为 4 种:普通文件、
目录文件、链接文件和设备文件。

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc ,char **argv)
{
	int fd,size;
	char *buf = "hello,I'm Webee,This is file io test!";
	char buf_r[20];
	int len = strlen(buf);
	/* 首先调用 open 函数,如果当前目录下没有 hello.c 则创建
	* 以读写方式打开文件,并指定权限为可读可写
	*/
	if((fd = open("./hello.c",O_CREAT | O_TRUNC | O_RDWR,0666))<0)
	{
		/* 错误处理 */
		printf("open fail\n");
		exit(1);
	}
	else
	printf("open file:hello.c fd = %d\n",fd);
	/* 调用 write 函数,将 buf 中的内容写入 hello.c */
	if((size = write(fd,buf,len) ) < 0)
	{
		
		printf("write fail\n");
		exit(1);
	}
	else
		printf("write: %s\n",buf);
	printf("len is %d ",len);
	/* 调用 lseek 函数将文件指针移到文件起始位置,并读出文件中的 15 个字
	节 */
		lseek(fd,0,SEEK_SET);
	if((size = read(fd,buf_r,15)) <0)
	{
			printf("read fail\n");
		exit(1);
	}
	else
	{
		buf_r[15] = '\0';
		printf("read from hello.c and the content is %s\n",buf_r);
	}
	/* 最后调用 close 函数关闭打开的文件 */
	if(close(fd) < 0)

	{
		printf("close fail\n");
		exit(1);
	}
	else
		printf("close hello.c\n");
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值