/**{{{
* Copyright (C) 2021YunHai Tech. Ltd
* All rights reserved.
*
* FileName :xxx.c
* Author :wanghaiyun
* Email :amn2811@163.com
* Date :2021-02-12 14:55:51
* Version :1.0
* Description :
*
*
* Replaceversion:
* Author :
* Date :
* Description :
*//*}}}*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
static void sys_err(char *str)
{
perror(str);
exit(1);
}
int main(void)
{
FILE *fp;
if((fp = fopen("data.txt","r+")) == NULL)
{
sys_err("fopen");
}
//src 要插入的目標字串
char src[] = "GOOGLE";
size_t len = strlen(src);
//1-定義需要插入的位置,檔案指標索引從0開始,3表示從第三個字符依次往后移動
long insertpos = 3;
//2-獲取當前檔案大
if( fseek(fp,0L,SEEK_END) == -1)
{
sys_err("fseek line 47 error");
}
//nwpos 打開檔案的大小
long nwpos;
if( (nwpos = ftell(fp)) == -1)
{
sys_err("ftell error line 55");
}
//3-判斷intsertpos與下一個合法的插入點的位置關系
if(insertpos > nwpos)
{
//表示正常的在檔案末尾插入,此種情況最為簡單
insertpos = nwpos;
}
else if(insertpos <nwpos)
{
//這里需要把插入點及其之后的資料往后依次移動
//如果最終移動成功,最后一個插入位置的索引
long target_final_pos = nwpos + len;
//未插入src目標字串時,下一個合法的插入點
long cur_final_pos = nwpos;
//計算插入點到最有一個有效字符的長度
int _len = nwpos - insertpos;
//定義每次移動的步長 step
long step = 1024;
if( step > _len)
{
step = _len;
}
//計算需要移動的次數
size_t count = _len/step;
//定義buffer,先把檔案讀出來,然后在寫入,類似于兩個變數交換的中間變數
char buffer[step];
//定義回圈因子
long i;
//判斷余數
long rest_charecter = _len%step;
//開始for回圈
for(i=0;i<count;i++)
{
cur_final_pos = cur_final_pos - step ;
if ( fseek ( fp,cur_final_pos,SEEK_SET) == -1 )
{
sys_err("fseek error line 95");
}
//讀取到buffer
if ( fread(buffer,step,1,fp) != 1)
{
sys_err("fread error line 102");
}
//計算要插入的位置
target_final_pos = target_final_pos - step;
if ( fseek ( fp,target_final_pos,SEEK_SET) == -1 )
{
sys_err("fseek error line 109");
}
//開始寫入
if ( fwrite(buffer,step,1,fp) !=1 )
{
sys_err("fwrite error! line 114");
}
printf("i=%lu,buffer=%s\n",i,buffer);
}
printf("rest_charecter=%lu\n",rest_charecter);
if ( rest_charecter != 0)
{
cur_final_pos = cur_final_pos - rest_charecter ;
if ( fseek ( fp,cur_final_pos,SEEK_SET) == -1 )
{
sys_err("fseek error line 95");
}
//讀取到buffer
if ( fread(buffer,rest_charecter,1,fp) != 1)
{
sys_err("fread error line 102");
}
//計算要插入的位置
target_final_pos = target_final_pos - rest_charecter;
if ( fseek ( fp,target_final_pos,SEEK_SET) == -1 )
{
sys_err("fseek error line 109");
}
//開始寫入
if ( fwrite(buffer,rest_charecter,1,fp) !=1 )
{
sys_err("fwrite error! line 114");
}
}
printf("buffer=%s\n",buffer);
}
//插入需要插入的字串,檔案偏移量為insertpos
if( fseek(fp,insertpos,SEEK_SET) == -1 )
{
sys_err("fseek error line 121");
}
if( fwrite(src,len,1,fp) < 1 )
{
sys_err("fwrite error line 126");
}
fclose(fp);
puts("end and success");
exit(0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259564.html
標籤:其他
上一篇:error: (-215:Assertion failed) !_src.empty() in function ‘cv::cvtColor‘:
下一篇:藍橋杯基礎練習 楊輝三角形
