C函数在文件中的特定位置插入文本而不覆盖现有文本 [英] C function to insert text at particular location in file without over-writing the existing text

查看:16
本文介绍了C函数在文件中的特定位置插入文本而不覆盖现有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序,它将一个文件作为输入,每当它找到长度 > 80 的行时,它都会向该文件添加 和 以使其最大宽度为 80 个字符.

I have written a program which takes a file as input and whenever it finds a line with length > 80, it adds and to that file to make it 80 chars in width max.

问题是,每当长度超过 80 时,我都使用 fseek 插入 和 ,因此它会覆盖该行中超过长度 80 的两个字符.有没有一种方法可以插入文本而不覆盖现有的文本?

The problem is that I have used fseek to insert and whenever the length exceeds 80, so it overrides two characters of that line which exceeds length 80. Is there a way using which I can insert text without overriding the existing text?

这是我的代码:-

#include<stdio.h>
#include<string.h>

int main(int argc, char *argv[])
{
  FILE *fp1,*fp2;
  int prev=0,now=0;
  char ch;
  int flag=0;
  long cur;
  fp1=fopen(argv[1],"r+");
  if(fp1==NULL){
    printf("Unable to open the file to read. Program will exit.");
    exit(0);
  }
  else{
    while((ch=fgetc(fp1))!=EOF){
      if(ch!=' ' && ch!='
'){
        now=now+1;
      }
      else{
        if(now>=80){
            fseek(fp1,cur,SEEK_SET);
            fputc('\',fp1);
            fputc('
',fp1);
            now=0;
            continue;
        }
        if(ch=='
'){
          flag=0;
          now=0;
          continue;
          }
        else{
          prev=now;
          cur=ftell(fp1);
        }
        now=now+1;
      }
    }
  }
  fclose(fp1);
  return 0;
}

要运行它,您需要执行以下操作:-

To run it, you need to do following:-

user@ubuntu$ cc xyz.c
user@ubuntu$ ./a.out file_to_check.txt

推荐答案

不,没有办法将字符插入到现有文件中.您将需要使用第二个文件来执行此操作.

No, there's no way to insert characters into an existing file. You will need to use a second file to do that.

这篇关于C函数在文件中的特定位置插入文本而不覆盖现有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆