一、read函数:
1.函数包含头文件:
#include <unistd.h>
2.函数原型:
ssize_t read(int fd, void *buf, size_t count);
3.函数参数:
① fd——文件描述符
② buf——一块指定的内存空间
③ count——指定的要读取的字节数
4.函数返回值:
成功返回读取的字节数,出错返回 -1并设置 errno,如果在调read之前已到达文件末尾,则这次read返回0。
注意 :对文件操作完之后要及时的close文件,为了 :①更早的释放所占用的系统资源 ②更早的将文件置于更安全的状态
5.demo
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int fd;
int n_write;
int n_read;
char *buf = "dengerbao zhende henshuai";
char *readBuf;
fd = open("./file1",O_RDWR);
if(fd == -1){//判断open函数是否成功打开指定路径的文件
printf("open failed!\n");
}else{
printf("open success!\n");
}
// ssize_t write(int fd, const void *buf, size_t count);
n_write = write(fd,buf,strlen(buf));
// 使用strlen而不是sizeof的原因:linux下指针占4个字节,64linux则占8个字节,很明显不能用于此
if(n_write == -1){
printf("write error!\n");
}else{
printf("write %d byte to file\n",n_write);
}
// off_t lseek(int fd, off_t offset, int whence);
lseek(fd,0,SEEK_SET);
// 使用lseek函数让文件读写位置移动到头部,不然读写位置在尾端会导致read函数读取不到数据
readBuf = (char *)malloc(sizeof(char)*n_write);
n_read = read(fd,readBuf,n_write);
printf("readBuf:%s\n",readBuf);
lseek(fd,0,SEEK_END);
// 使用lseek函数让文件读写位置重新回到尾部,有始有终
close(fd);//及时关闭文件,以免多占用资源或损坏文件
return 0;
}
6.补充 :lseek函数