Linux 文件I/O编程

学习linux文件编程之前,首先先了解一点关于linux中文件的知识,这样好为以后学习做准备。

1.Linux 中的文件主要分为4种:普通文件、目录文件、链接文件和设备文件。

2.不带缓存的文件I/O 操作:主要用到5 个函数:openreadwritelseekclose

接着我们就看看这几个函数是详细用法

3.open函数是用于打开或创建文件,在打开或创建文件时可以指定文件的属性及用户的权限等各种参数。

函数原型 int open(const char *pathnameflagsint perms)函数返回值 成功:返回文件描述符 失败: -1

下面是关于这个函数的应用举例

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

int main() {
	//fd文件描述符= _CREAT(创建)|O_TRUNC(存在)|O_WRONLY(可读写的方式) 
	int fd;
	if ((fd=open("/usr/wangjie/file/test.c", O_CREAT|O_TRUNC|O_WRONLY, 0600))<0) {
		perror("open error!!!\n");
	} else {
		printf("open test.c success!!! fd= %d\n", fd);

	}
	if (close(fd)<0) {
		perror("close error!!!\n");
		exit(1);
	} else
		printf("close  test.c success!!\n");
	exit(0);
}


运行的结果如图


学会了打开文件,接着就是关闭一个文件的使用方法,在关闭一个文件时候我们会用到文件操作的几个函数,这样就可以对一个文件进行简单的读写操作,

4.read函数是用于将指定的文件描述符中读出数据。当从终端设备文件中读出数据时,通常一次最多读一行。

函数原型 ssize_t read(int fd,void *buf,size_t count) 函数返回值 成功:读到的字节数 0:已到达文件尾 -1:出错

5.write函数是用于向打开的文件写数据,写操作从文件的当前位移量处开始。若磁盘已满或超出该文件的长度,则write函数返回失败。

函数原型 ssize_t write(int fd,void *buf,size_t count)函数返回值 成功:已写的字节数 -1:出错

6.lseek函数是用于在指定的文件描述符中将文件指针定位到相应的位置。

函数原型 off_t lseek(int fd,off_t offset,int whence) 函数返回值 成功:文件的当前位移 -1:出错

7. close函数是用于关闭一个打开文件。当一个进程终止时,它所有已打开的文件都由内核自动关闭,很多程序都使用这一功能而不显示地关闭一个文件。

函数原型 int close(int fd) 函数返回值 0:成功 -1:出错

下面是关于这个函数的应用举例

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
int i, fd, size, len;
char * buf="this is the buffer write to the test.c ";
char buf_r[20];
len=strlen(buf);
if ((fd=open("/usr/wangjie/file/test.c", O_CREAT|O_TRUNC|O_RDWR, 0666))<0) {
perror("open test.c error!!\n");
exit(1);
} else
printf("open file test.c success!!! the fd =%d\n", fd);
//使用write函数 将buf中的内容写入到打开的文件中 
if ((size=write(fd, buf, len))<0) {
perror("write test.c error!!!\n");
exit(1);
} else
printf(
"Write to the file test.c success!! \nthe buffer string is %s\n ",
buf);
//调用lseek函数从0开始读出文件中的15个字节 
lseek(fd, 0, SEEK_SET);
if ((size=read(fd, buf_r, 15))<0) {
perror("read string error!!\n");
exit(1);
} else {
printf("read string from test.c is %s\n", buf_r);
//调用close函数关闭文件
if (close(fd)<0) {
perror("close test.c error!!\n");
exit(1);
} else
printf("close test.c success!!\n");
exit(0);
}
}


运行的结果截图如下:


为了解决文件资源共享产生竞争,就可以用文件中的fcntl函数给文件上锁来解决这个问题。

8.fcntl 建立记录锁

Linux 通常采用的方法是给文件上锁,来避免共享的资源产生竞争的状态 ,文件锁包括建议性锁和强制性锁 .
建议性锁要求每个上锁文件的进程都要检查是否有锁存在,并且尊重已有的锁 ,一般情况下,内核和系统都不使用建议性锁
强制性锁是由内核执行的锁,当一个文件被上锁进行写入操作的时候,内核将阻止其他任何文件对其进行读写操作
记录锁又可分为读取锁 (共享锁 )和写入锁(排斥锁)
函数原型 int fcnt1(int fd,int cmd,struct flock *lock)函数返回值 成功: 0 -1:出错

下面是一个简单的文件上读取锁的例子

#include<stdio.h>
#include<unistd.h>
#include<sys/file.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>

void lock_set(int fd, int type) {

	struct flock lock;
	lock.l_whence=SEEK_SET;
	lock.l_start=0;
	lock.l_len=0;
	while (1) {

		lock.l_type=type;
		//根据不同的type值给文件上锁或者解锁 
		if ((fcntl(fd, F_SETLK, &lock))==0) {

			if (lock.l_type==F_RDLCK)
				printf("read locked set by %d \n", getpid());
			else if (lock.l_type==F_WRLCK)
				printf("read locked set by %d \n", getpid());
			else if (lock.l_type==F_UNLCK)

				return;
		}
         
		fcntl(fd, F_GETLK, &lock);
		// 判断文件是否可以上锁 
		if (lock.l_type!=F_UNLCK) {
        //如果上了读取锁 
			if (lock.l_type==F_RDLCK)
				printf("read lock already set by %d\n", lock.l_pid);
		 //如果上了写入锁 
			else if (lock.l_type==F_WRLCK)
				printf("write lock already set by %d\n", lock.l_pid);
			getchar();

		}

	}
}
int main() {

	int fd;
	if ((fd=open("/usr/wangjie/file/test.c", O_RDWR|O_CREAT, 0666))<0) {
		perror("open test.c error!!\n");
		exit(1);

	}
	//给文件上读取锁 
	lock_set(fd, F_RDLCK);
	getchar();
	//给文件解锁 
	lock_set(fd, F_UNLCK);
	getchar();
	close(fd);
	exit(0);

}



运行结果如下



下面是一个简单的文件上写入锁的例子

#include<stdio.h>
#include<unistd.h>
#include<sys/file.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>

void lock_set(int fd, int type) {

	struct flock lock;
	lock.l_whence=SEEK_SET;
	lock.l_start=0;
	lock.l_len=0;
	while (1) {

		lock.l_type=type;
		if ((fcntl(fd, F_SETLK, &lock))==0) {

			if (lock.l_type==F_RDLCK)
				printf("read locked set by %d \n", getpid());
			else if (lock.l_type==F_WRLCK)
				printf("read locked set by %d \n", getpid());
			else if (lock.l_type==F_UNLCK)

				return;
		}

		fcntl(fd, F_GETLK, &lock);
		if (lock.l_type!=F_UNLCK) {
			if (lock.l_type==F_RDLCK)
				printf("read lock already set by %d\n", lock.l_pid);
			else if (lock.l_type==F_WRLCK)
				printf("write lock already set by %d\n", lock.l_pid);
			getchar();

		}

	}

}

int main() {

	int fd;
	if ((fd=open("test.c", O_CREAT|O_RDWR, 0666))<0) {
		perror("open the test.c error!!!");
		exit(1);
	}
	//给文件上写入锁 
	lock_set(fd, F_WRLCK);
	getchar();
	//给文件解锁 
	lock_set(fd, F_UNLCK);
	getchar();
	close(fd);
	exit(0);

}


运行结果截图如下:



重新打开一个终端运行,这时候就会发现写入锁已经上过了


fcntl函数解决了文件的共享问题,但是如何处理I/O复用的情况,接下来就介绍解决处理I/O复用的情况,首先先了解I/O处理的模型有哪些

9.I/O 处理的模型有5

1 阻塞 I/O模型 2、非阻塞模型 3I/O多路转接模型 4、信号驱动 I/O 模型 5、异步 I/O模型

10.select函数的I/O多路转接模型是处理I/O复用的一个高效的方法

函数原型int select(int numfds,fd_set *readfds,fd_set *writefdsfd_set *exeptfds,struct timeval *timeout)

下面是讲一个文件的内容读出,每个一定的时间写入另一个文件的例子

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
#include<fcntl.h>
int main() {

	int fds[2];
	char buf[20];
	int i, rc, maxfd;
	fd_set inset1, inset2;
	struct timeval tv;
	if ((fds[0]=open("/usr/wangjie/file/test.c", O_RDWR|O_CREAT, 0666))<0) {
		perror("open test.c error!!!\n");

	}
	if ((fds[1]=open("/usr/wangjie/file/test1.c", O_RDWR|O_CREAT, 0666))<0) {
		perror("open test1.c error!!!\n");

	}
	if ((rc=write(fds[0], "good good study day day up!!!\n", 20)));
	printf("rc=%d\n", rc);
	lseek(fds[0], 0, SEEK_SET);
	//取出两个文件描述符的较大者 
	maxfd=fds[0]>fds[1] ? fds[0] : fds[1];
	//初始化inset1 并加入相应的描述集 
	FD_ZERO(&inset1);
	FD_SET(fds[0], &inset1);
	FD_ZERO(&inset2);
	FD_SET(fds[1], &inset2);
	tv.tv_sec=2;
	tv.tv_usec=0;
	//判断文件描述符是否就绪 
	while (FD_ISSET(fds[0], &inset1)||FD_ISSET(fds[1], &inset2))

	{
          // 调用select函数 
		if (select(maxfd+1, &inset1, &inset2, NULL, &tv)<0)
			perror("select error");
		else {

			if (FD_ISSET(fds[0], &inset1))

			{

				rc=read(fds[0], buf, 20);
				if (rc>0) {
					buf[rc]='\0';
					printf("read from test.c is  %s\n", buf);

				} else
					perror("read test.c  error!!\n");

			}
			if (FD_ISSET(fds[1], &inset2)) {
				rc=write(fds[1], buf, 20);
				if (rc>0) {
					buf[rc]='\0';

					printf("rc=%d write  to  test1.c %s\n", rc, buf);

				} else
					perror("write error!!\n");

				sleep(10);

			}

		}

	}
	exit(0);

}



运行结果截图如下:


源代码下载地址:http://download.csdn.net/detail/wjky2014/5123435

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Android

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值