参考文章:(6条消息) Linux编程基础 2.1:Linux文件系统与操作_HenrySmale的博客-CSDN博客
指导老师:张恒儒
本节课程学习了Linux文件系统级操作相关的几个函数,并尝试运行,分享心得如下:
文件I/O
open()
read()
write()
lseek()
close()
上述函数用法及功能在本人老师所编辑的文章上查看,这里不做过多解释。
案例代码
#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);
if(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_CUR)!= tempFileSize){
read(tempFd, tempBuf, 1024);
printf("%s\n", tempBuf);
}//of while
close(tempFd);
return 0;
}//of main
代码分析:
1):打开文件 使用了open()函数,调用了O_TRUNC参数,表示覆写,及会覆盖之前的内容;
2):写入数据
3):读取数据 使用了偏移量进行读取数据,从0开始进行读写。
将代码在虚拟机上编辑,在终端上运行,如下所示:
运行完成后,点开文档,发现内容与输入一样。
心得体会:
1.在使用open函数调用O_TRUNC参数时,表示覆写原来的文档,并不会重新创建;
2.今天了解了关于文件操作的几种函数,知道了llinux下如何进行系统编程,掌握了几种对文件操作的方式;
3.明白了本门课程的学习方向,即Linux下的系统编程。