- 前言
- 一、文件I/O相关函数
- 二、文件案例
- 1.案例代码
- 2.运行结果
- 总结
前言
提示:这里可以添加本文要记录的大概内容:
这是Linux编程基础第一课,主要是文件系统与操作,本次文章是记录上课收获,由于我还没有安装Ubuntu,所以暂时在Redhat下运行。
提示:以下是本篇文章正文内容,下面案例可供参考
一、文件I/O相关函数open()
read()
write()
lseek()
close()
代码如下(示例):
#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); 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("%sn", tempBuf); }//of while close(tempFd); return 0; }//of main
运行结果
一:先需要创建一个空文件,使用touch命令
二:编译代码 gcc main.c ./a.out(没有完全截完图)
三:直接输入
总结
本次任务共需完成三个基本目标:打开文件,写入数据,读取数据。
首先是在写代码上,对变量,形参的规范上发生了变化,这是与C语言稍微有一点不同的。编译的时候也出现了一些问题,首先是代码错误,导致根本编译不出来,其次是file open error,就是由于没有先创建文件。还需要不断积累经验。



