学习Linux编程基础 2.1:Linux文件系统与操作心得:
https://blog.youkuaiyun.com/search_129_hr/article/details/124454969
本节课主要学习了文件I/O操作的一些相关函数:
文件读写操作部分相关函数
1.open()
2.read()
3.write()
4.lseek()
5.close()
1.open()
打开或创建一个文件,存在于系统函数库fcntl.h中
函数声明:
int open(const char *pathname,int flags[,mode_t mode]);
参数分析:
pathname:文件路径
flag:访问模式,常用的宏见下表:
mode:设置新文件权限(只有第二个参数flag=O_CREAT)才会起作用,部分权限:
返回值:
调用成功,返回文件描述符
不成功,返回-1
示例:创建文件
open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode);
或者
int create(const char *pathname, mode_t mode);
2.read()
从已经打开的设备或文件中读取数据,存在于unistd.h库中
函数声明:
ssize_t read(int fd, void *buf, size_t count);
参数分析:
fd:从open或create函数返回的文件描述符
bf:缓冲区
count:计划读取的字节数
返回值:
ssize_t:
正数:请求读取的字节数
0:文件长度有限,长度超过读写位置距离文件末尾的位置:第一次返回读取的字节数,第二次返回0
-1:读取文件出错
3.write()
向已经打开的设备或文件中写入数据,存在于unistd.h库中
参数与read()函数相同
返回值:
返回写入的字节数并设置error
4.lseek()
对文件偏移量进行修改,存在于unistd.h库中
函数声明:
ssize_t write(int fd, off_t offset, int whence);
参数分析:
fd:从open或create函数返回文件描述符
offset:对文件偏移量进行设置,参数可正可负
whence:控制设置当前文件偏移量的方法
whence | 文件偏移量 |
---|---|
SEEK_SET | offset |
SEEK_CUR | 当前偏移量+offset |
SEEK_END | 文件长度+offset |
返回值:
设置成功:返回新的偏移量
不成功:-1
5.close()
函数声明:
int close(int fd);
位于unistd.h库中
返回值:
成功:0
不成功:-1
**
测试案例:
**
使用open函数打开或创建一个文件,将文件清空,使用write函数在文件中写入数据,并使用read函数将数据读取并打印。
#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_CUT)!= tempFileSize){
read(tempFd, tempBuf, 1024);
printf("%s\n", tempBuf);
}//of while
close(tempFd);
return 0;
}//of main
运行结果:
总结:文件系统方便我们对文件进行操作,还需要进一步学习。