栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

linux文件系统与操作

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

linux文件系统与操作

linux文件系统与操作 学习目标:

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

一、 open函数

①引入头文件

#include 
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 
ssize_t read(int fd, void *buf, size_t count);

②read函数参数说明:

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

①引入头文件

#include 
ssize_t write(int fd, void *buf, size_t count);

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

四. lseek函数

①引入头文件

#include 
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 
int close(int fd);
六. 案例实践

①老师代码修改过的代码

#include 
#include 
#include 
#include 
#include 
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("%sn", tempBuf);
	}//of while
	close(tempFd);
	return 0;
}//of main

②运行结果



总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853272.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号