昨天的时候我们了解到了这么一个当我们,当我们想要读取文本内容的时候,却发现了这么一个问题,我们不能读取到任何东西,昨天讲的不是很清楚今天决定重新再来一遍并优化我们的代码:
==================================================================
当我们打开一个空白文件的时候,开始我们的光标默认位置就是在最开始的部分,我们的光标便如图所示:
这时候我们如果读取,他是会从光标之后开始读取,这个规则我也不知道是为什么,但这就是它的设计者定的,如果我们输入了一串字符,这时候光标的位置就在这了:
这个时候我们的光标后面还是无内容的,导致输出显示不了任何文本内容 ,因此我们需要关闭再打开,让光标回到初始的默认位置即第一个位置。
这是比较弱智的方式,而我现在也了解到了一个新的方式,没错!又是新的命令!让我们来看看!
打开终端,输入命令:
man lseek
让我们查看一下他的使用方式并使用:
#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 fd;
char *buf = "Hello Linux!";
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("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);
}
//close(fd);
//fd = open("./file1",O_RDWR);
lseek(fd, 0, SEEK_SET); //本次使用的操作指令
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write);
int n_read=read(fd,readbuf,n_write);
printf("read: %d ,context: %s",n_read,readbuf);
close(fd);
return 0;
}
其中,lseek(fd,0,SEEK_SET)的使用代替了close(fd)然后fd=open()关闭再打开的一个操作,节省代码空间,提高运行速率,其中 0表示光标需要回到的位置,SEEK_SET是针对文件初始头部的偏移值,偏移值是0,所以我们从头开始偏移0个字节,因此不变还是在最开始的初始默认位置;我们来看看编译的结果:
完美!
同样我们也可以用这类命令,还可以我们的文件大小,我们这么来操作:
lseek(fd , 0 ,SEEK_END);
它的含义是什么? 含义是从尾部开始便宜向前便宜0个字节,即读取到距离尾部0个字节的地方
我们这边继续来编写一下命令:
#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 fd;
char *buf ="Hello Linux!";
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("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);
}
//close(fd);
//fd = open("./file1",O_RDWR);
int filesize = lseek(fd,0,SEEK_END);
char *readbuf;
readbuf=(char *)malloc(sizeof(char)*n_write);
int n_read=read(fd,readbuf,n_write);
printf("the fileize is : %d \n",filesize); //修改的位置在这!
close(fd);
return 0;
}
我们修改一下结尾打印的东西,只显示一共多少字节即文件的大小,我们定义为 int filesize,将lseek读取的字节数赋值给filesize并在后面打印输出,让我们编译一下看看结果!
我们可以看到 filesize=13,我们在终端使用命令来看看文件大小是否也是13呢?
那么我们使用 命令 ls -l ,可以看到我们程序所编写的 file1 文件的大小也为13!
正是完成!我们今天的任务到此结束!睡觉!现在是凌晨1:44!明天继续起来好好学习好好锻炼!