读取文件手册
函数定义:ssize_t read(int fd, void * buf, size_t count);
函数说明:read()会把参数fd所指的文件传送count 个字节到buf 指针所指的内存中。
返回值:返回值为实际读取到的字节数, 如果返回0, 表示已到达文件尾或是无可读取的数据。若参数count 为0, 则read()不会有作用并返回0。另外,以下情况返回值小于count。
代码实现
#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 = "chenglong henshuai?";
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\n");
}
}
printf("fd = %d\n",fd);
int n_write = write(fd,buf,strlen(buf));
// write(fd,buf,sizeof(buf));
if(n_write != -1){ //判断是否写入成功,失败返回-1
printf("write %d byte to file1\n",n_write);
}
char *readBuf; //野指针
readBuf = (char *)malloc(sizeof(char )*n_write + 1); //读取开辟写入+1的大小,强转成char型指针
int n_read = read(fd,readBuf,n_write);
printf("read %d,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}
fd = 3
write 19 byte to file1
read 0,context:
问题发现:无法读取文件(光标的问题)
光标位置在chenglong henshuai?问号后面,读取的是光标后面的空内容。
解决方法:1.重新打开文件(老土法) 2.光标移动到头头(好方法)
#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 = "chenglong henshuai?";
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\n");
}
}
printf("fd = %d\n",fd);
int n_write = write(fd,buf,strlen(buf));
// write(fd,buf,sizeof(buf));
if(n_write != -1){
printf("write %d byte to file1\n",n_write);
}
close(fd);
fd = open("./file1",O_RDWR);//写完后关闭文件,重新打开
char *readBuf;
readBuf = (char *)malloc(sizeof(char )*n_write + 1);
int n_read = read(fd,readBuf,n_write);
printf("read %d,context:%s\n",n_read,readBuf);
close(fd);
return 0;
}
结果:
fd = 3
write 19 byte to file1
read 19,context:chenglong henshuai?