linux文件系统与操作

linux文件系统与操作

学习目标:

了解linux文件系统与操作的原理
学习文件I/O相关的函数作用及其运用
通过实例巩固

一、 open函数

①引入头文件

#include <fcntl.h>
int open(const char *pathname, int flags[, mode_t mode);

②open函数参数说明:

pathname:待打开文件的文件路径名;
flags:访问模式,常用的宏有:
– O_RDONLY:只读
– O_WRONLY: 只写
– O_RDWR: 读写
– O_CREAT: 创建一个文件并打开
– O_EXCL: 测试文件是否存在,不存在则创建
– O_TRUNC: 以只写或读写方式成功打开文件时,将文件长度截断为0
– O_APPEND: 以追加方式打开文件

二、read函数

①引入头文件

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

②read函数参数说明:

fd	为从open或create函数返回的文件描述符,简单来说fd就是open一个文件后赋的值。
buf	缓冲区,就是把文件中的内容按指定大小存在buf中后续进行输出
count	最大读取的长度,即指定要读去数据的长度或者大小

三.write函数

①引入头文件

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

②write函数参数说明: 同read函数

四. lseek函数

①引入头文件

#include <unistd.h>
ssize_t write(int fd, off_t offset, int whence);

②lseek函数参数说明:

fd: 从open或create函数返回的文件描述符
offset: 对文件偏移量的设置,参数可正可负
whence: 控制设置当前文件偏移量的方法
– whence = SEEK_SET: 文件偏移量被设置为offset
– whence = SEEK_CUR: 文件偏移量被设置为当前偏移量+offset
– whence = SEEK_END: 文件偏移量被设置为文件长度+offset

五. close函数

①引入头文件

#include <unistd.h>
int close(int fd);

六. 案例实践

①老师代码修改过的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(){
	int tempFd = 0;
	char tempFileName[20] = "test.txt";
	//Step 1. open the file.
	tempFd = open(tempFileName, O_RDWR|O_EXCL|O_TRUNC, S_IRWXG);
	if(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	//Step 2. write the data.
	int tempLen = 0;
	char tempBuf[100] = {0};
	scanf("%s", tempBuf);
	tempLen = strlen(tempBuf);
	write(tempFd, tempBuf, tempLen);
	close(tempFd);
	//Step 3. read the file
	tempFd = open(tempFileName, O_RDONLY);
	int(tempFd == -1){
		perror("file open error.\n");
		exit(-1);
	}//of if
	off_t tempFileSize = 0;
	tempFileSize = lseek(tempFd, 0, SEEK_END);
	lseek(tempFd, 0, SEEK_SET);
	while(lseek(tempFd, 0, SEEK_CUT)!= tempFileSize){
		read(tempFd, tempBuf, 1024);
		printf("%s\n", tempBuf);
	}//of while
	close(tempFd);
	return 0;
}//of main

②运行结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

总结

对系统级程序设计这门课程有了个初步的了解
注意C语言代码书写规范
对文件I/O相关的函数进行实践运用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值