1、读取文件函数原型介绍
ssize_t read(int fd,void*buf,size_t count)
参数说明:
fd: 是文件描述符
buf:为读出数据的缓冲区;
count: 为每次读取的字节数(是请求读取的字节数,读上来的数据保存在缓冲区buf中,同时文件的当前读写位置向后移)
返回值:
成功:返回读出的字节数
失败:返回-1,并设置errno,如果在调用read,之前到达文件末尾,则这次read返回0
2、读取文件函数示例
打开终端,输入以下指令:
vi demo2.c
接着输入如下代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>int main()
{int fd;char *buf = "asdfgh!"; fd = open("./file1",O_RDWR);if(fd == -1){printf("open file1 failed\n");fd = open("./file1",O_RDWR|O_CREAT,0600);if(fd > 0){printf("create file1 success!\n");}}printf("open susceess : fd = %d\n",fd);// ssize_t write(int fd, const void *buf, size_t count);int n_write = write(fd,buf,strlen(buf));if(n_write != -1){printf("write %d byte to file\n",n_write);}char *readBuf;readBuf = (char *)malloc(sizeof(char)*n_write + 1);
// ssize_t read(int fd, void *buf, size_t count);int n_read = read(fd, readBuf, n_write);printf("read %d ,context:%s\n",n_read,readBuf);close(fd);return 0;
}
保存退出后,输入如下指令:
gcc demo2.c
./a.out
3、光标移动操作
从运行结果可以看到,并未读取到内容,因为读取时候光标不在最左侧,因此需要进行光标设置。
光标函数原型:
off_t lseek(int fd, off_t offset, int whence);
函数参数
fd:文件描述符
offset:偏移量
whence:位置
- SEEK_SET:The offset is set to offset bytes. offset为0时表示文件开始位置。
- SEEK_CUR:The offset is set to its current location plus offset bytes. offset为0时表示当前位置。
- SEEK_END:The offset is set to the size of the file plus offset bytes. offset为0时表示结尾位置
函数返回值
- 成功返回当前位置到开始的长度
- 失败返回-1并设置errno
首先输入如下指令:
vi demo2.c
输入以下代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>int main()
{int fd;char *buf = "asdfghi!"; fd = open("./file1",O_RDWR);if(fd == -1){printf("open file1 failed\n");fd = open("./file1",O_RDWR|O_CREAT,0600);if(fd > 0){printf("create file1 success!\n");}}printf("open susceess : fd = %d\n",fd);int n_write = write(fd,buf,strlen(buf));if(n_write != -1){printf("write %d byte to file\n",n_write);}char *readBuf;readBuf = (char *)malloc(sizeof(char)*n_write + 1); lseek(fd, 0, SEEK_SET);int n_read = read(fd, readBuf,100);printf("read %d ,context:%s\n",n_read,readBuf);close(fd);return 0;
}
保存,输入以下指令:
gcc demo2.c
./a.out
运行结果如下: