先看read函数的定义
- 看开始的代码
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main()
{
int fd;
char *buf="LLP IS MY WIEF!";
fd=open("./qqq.c",O_RDWR);
if(fd==-1)
{
printf("open file failed!\n");
fd=open("./qqq.c",O_RDWR|O_CREAT,0600);
if(fd>=0)
{
printf("creat file success!\n");
}
}
printf("open success!,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);
int n_read=read(fd,readBuf,n_write);//read函数就是讲返回为fd的文件中的n_write个数读到readBuf中。记住咯!
printf("read %d ,context: %s\n",n_read,readBuf);
close(fd);
return 0;
}
- 再来看看结果与我们想的是不是不一样。
咦!为什么read了0 个字节呢,理论上应该和write的一样多啊!这是因为我们的光标问题,当write函数运行结束时,光标正好停在“LLP IS MY WIFE!”最后感叹号后面。然后下一次读的时候就从感叹号后面读,所以什么都读不到了,为0!
那要怎么解决呢?有两种解决方法,第一种大不了重新来呗!在 read之前再重新打开这个文件,光标不就指向刚开始的时候了吗(记得在打开之前要先关闭此文件!)比如这样:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main()
{
int fd;
char *buf="LLP IS MY WIEF!";
fd=open("./qqq.c",O_RDWR);
if(fd==-1)
{
printf("open file failed!\n");
fd=open("./qqq.c",O_RDWR|O_CREAT,0600);
if(fd>=0)
{
printf("creat file success!\n");
}
}
printf("open success!,fd=%d\n",fd);
int n_write=write(fd,buf,strlen(buf));//buf和readBuf一定都是地址
if(n_write!=-1)
{
printf("write %d byte to file!\n",n_write);
}
close(fd);
fd=open("./qqq.c",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;
}
再来看看运行结果!
完美!
第二种方法用的更多!
用lseek
函数
可以这样写:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
int main()
{
int fd;
char *buf="LLP IS MY WIEF!";
fd=open("./qqq.c",O_RDWR);
if(fd==-1)
{
printf("open file failed!\n");
fd=open("./qqq.c",O_RDWR|O_CREAT,0600);
if(fd>=0)
{
printf("creat file success!\n");
}
}
printf("open success!,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;
// lseek(fd,0,SEEK_SET);
// lseek(fd,-n_write,SEEK_END);
// lseek(fd,-n_write,SEEK_CUR);这三种随便取一种都可,中间的数字为光标的相对偏移量,SEEK_SET代表起始光标,SEEK_END代表尾巴光标,SEEK_CUR代表程序当前光标。光标分正负,代表前后。
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;
}
结果运行正确
*在成功完成后,lseek()将从文件开始时以字节为单位返回结果偏移量定位。如果出现错误,则返回值-1,并将error设置为指示错误。
根据这个就可以计算文件的大小了。
int size=lseek(fd,0,SEEK_END);
// lseek(fd,-n_write,SEEK_END);
// lseek(fd,-n_write,SEEK_CUR);
printf("The size of file is:%d\n",size);