文章目录
- 有关文件I/O的函数
- 案列分析
前言
本篇文章主要记录了昨日上课的一些内容:有关文件i/o的函数和有关案列分析
提示:以下是本篇文章正文内容,下面案例可供参考
一、文件I/O
1.1 open函数
open()
打开文件
定义函数:
#include <fcntl.h>
int open(const char *pathname, int flags[, mode_t mode);
pathname:待打开文件的文件路径名;
flags:访问模式;
返回描述:
调用成功,返回一个文件描述符
不成功,返回-1
1.2 read函数
read()
读取文件
定义函数:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
fd: 从open或create函数返回的文件描述符
buf: 缓冲区
count: 读取数据的字节数
返回描述:
ssize_t: 有符号的size_t,有三种返回值
– 正数:请求读取的字节数
– 0: 文件长度有限,若读写位置距文件末尾只有20字节,该函数请求读取30字节,则第一次读取时返回值为20,第二次读取时,返回0
– -1: 读取文件出错
1.3 write函数
write()
写入文件
定义函数:
#include <unistd.h>
ssize_t write(int fd, void *buf, size_t count);
参数同read函数
返回描述:
返回写入的字节数或者-1并设置errno
1.4 lseek函数
lseek()
定义函数:
#include <unistd.h>
ssize_t write(int fd, off_t offset, int whence);
fd: 从open或create函数返回的文件描述符
offset: 对文件偏移量的设置,参数可正可负
whence: 控制设置当前文件偏移量的方法
– whence = SEEK_SET: 文件偏移量被设置为offset
– whence = SEEK_CUR: 文件偏移量被设置为当前偏移量+offset
– whence = SEEK_END: 文件偏移量被设置为文件长度+offset
返回描述:
成功:返回新的偏移量
不成功:-1
1.5 close函数
close()
定义函数:
#include <unistd.h>
int close(int fd);
返回描述:
成功:返回0
不成功:-1
二、案例分析
代码如下(示例):
#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
输出示例: