问题:
write函数调用之后,如果光标是在文件原有的字符之间那么写入的字符会替换原有字符,例如
H(光标)ello world,写入字符Q,得到结果HQllo world;
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
void my_err(const char *err_string,int line)
{
fprintf(stderr,"line:%d",line);
perror(err_string);
_exit(1);
}
int my_read(int fd)
{
int len;
int ret;
int i;
char read_buf[64];
if(lseek(fd,0,SEEK_END)==-1)
{
my_err("lseek",__LINE__);
}
if((len=lseek(fd,0,SEEK_CUR))==-1)
{
my_err("lseek",__LINE__);
}
if(lseek(fd,0,SEEK_SET)==-1)
{
my_err("lseek",__LINE__);
}
printf("len:%d\n",len);
if((ret=read(fd,read_buf,len))<0)
{
my_err("read",__LINE__);
}
//printf("%d",ret);
for(i=0;i<len;i++)
{
printf("%c",read_buf[i]);
}
printf("\n");
return ret;
}
int main()
{
int fd;
char write_buf[32]="Hello World";
char write_buf2[32]="Q";
if((fd=open("test.txt",O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR))==-1)
{
my_err("open",LINE);
}
else
{
printf("creat the file success\n");
}
if(write(fd,write_buf,strlen(write_buf))!=strlen(write_buf))
{
my_err("write",__LINE__);
}
printf("---------------------------------\n");
if(lseek(fd,1,SEEK_SET)==-1)
{
my_err("lseek",__LINE__);
}
if(write(fd,write_buf2,strlen(write_buf2))!=strlen(write_buf2))
{
my_err("write",__LINE__);
}
my_read(fd);
close(fd);
return 0;
}
如果想保留之后的字符,是不是只能先保存下来等写完之后再写回去,但是又觉得太占用资源了,应该是有其他办法的,但是也没找到。、
想问问这种情况怎么解决(写入数据但是保留光标之后数据使其不被替换)