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相关的函数进行实践运用