C函数插入在特定位置的文本文件中无过写现有文本 [英] C function to insert text at particular location in file without over-writing the existing text
问题描述
我写了一个程序,它需要一个文件作为输入,一发现长度> 80线,它增加了\\和\\ n至该文件,使其80个字符的宽度最大。
问题是,我已经使用fseek的插入\\和\\ n只要长度超过80,因此它将覆盖该行超过80长度的两个人物有没有用,我可以插入文本没有覆盖的方式存在文本?
下面是我的code: -
#包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;INT主(INT ARGC,CHAR *的argv [])
{
FILE * FP1,FP2 *;
INT preV = 0,现= 0;
焦炭CH;
INT标志= 0;
长CUR;
FP1 = FOPEN(的argv [1],R +);
如果(FP1 == NULL){
的printf(无法打开文件中读取程序将退出。);
出口(0);
}
其他{
而((CH =龟etc(FP1))!= EOF){
如果(CH ='!'和;&安培;!CH ='\\ n'){
现在= NOW + 1;
}
其他{
如果(现> = 80){
fseek的(FP1,CUR,SEEK_SET);
的fputc('\\\\',FP1);
的fputc('\\ n',FP1);
现在= 0;
继续;
}
如果(CH =='\\ n'){
标志= 0;
现在= 0;
继续;
}
其他{
preV =现在;
CUR = FTELL(FP1);
}
现在= NOW + 1;
}
}
}
FCLOSE(FP1);
返回0;
}
要运行它,你需要做以下几点: -
用户@ Ubuntu的$ CC xyz.c
用户@ Ubuntu的$ ./a.out file_to_check.txt
没有,有没有办法插入字符到现有文件。您将需要使用另一个文件来做到这一点。
I have written a program which takes a file as input and whenever it finds a line with length > 80, it adds \ and \n to that file to make it 80 chars in width max.
The problem is that I have used fseek to insert \ and \n 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?
Here is my code:-
#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!='\n'){
now=now+1;
}
else{
if(now>=80){
fseek(fp1,cur,SEEK_SET);
fputc('\\',fp1);
fputc('\n',fp1);
now=0;
continue;
}
if(ch=='\n'){
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屋!