我有一个带有一些文本的txt文件。我要做的就是在该文件中找到一个给定的单词,并用一个新的给定单词对其进行更改。这些词语和文本文件的名字将在命令提示与所述格式被提供C> findword <old word> <new word> <filename>
,其中findword
是可执行文件。一个单词将以a '.'
,a' '
或a结尾'\n'
。单词结束后,如果我们有多余的空格或换行符,我们将直接忽略它。我为此编写了以下代码,并在r+
模式下打开了文件。我不想在这里使用临时文件。所有更新应在同一文件上进行。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char *argv[])
{
if(argc != 4)
{
printf("Improper number of arguments\n");
exit(1);
}
FILE *fp = fopen(argv[3], "r+");
if(fp == NULL)
{
printf("Unable to open file\n");
exit(2);
}
char word[25];
int i, flag = 0, len, k;
char ch;
len = strlen(argv[1])+1;//assuming new and old words are of same length
for(i=0;1;i++)
{
word[i] = fgetc(fp);
if(word[i] == EOF)
{
break;
}
if((word[i] == ' ' || word[i] == '.' || word[i] == '\n') && (flag == 0))
{
word[i] = '\0';
if(strcmp(argv[1], word) == 0)
{
fseek(fp, -(len), SEEK_CUR);//To seek back to the start of the old word
k = fputs(argv[2], fp);//writing new word n place of old word
}
flag = 1;//whenever a word is formed, flag is set to 1
}
//Below code is used to check if next charcter is whitespace or alphabet, so that we can start forming a new word
ch = fgetc(fp);
if(ch == EOF)
{
break;
}
if((flag == 1) && (ch != ' ' && ch != '\n'))//if ch is whitespace or newline we have to simply ignore it.
{
i = -1;//i will get incremented to 0 in next iteration and we can start forming new word
flag = 0;//signifies we will be forming a new word from next iteration.
}
fseek(fp, -1, SEEK_CUR);
}
fclose(fp);
return 0;
}
现在,假设文本文件的单行写为This is business.
。当我写的CMD命令作为C> findword is zz test.txt
地方is
是旧词,其必须更换,zz
是新词,test.txt
是文本文件。执行此命令后,我期望将文本文件更新为,This zz business
但令我惊讶的是,该文本文件被重写为This zzubusiness.
。问题是更新单词后is
,后面的空格is
也被更新。在这种情况下,将其替换为character u
。我用不同的单词和文本文件尝试了此代码,发现之后的空格is
始终被下一个单词的第二个字符替换。例如:这里的空间被替换u
为单词的第二个字符business
。现在,我已经花了很多时间调试此代码,但是没有这样做。我知道这段代码不是很有效,但是我故意写它只是为了做一些实验。此代码有什么问题?fgetc()
与fputs()
在同一文件上同时使用它们有关吗?还是我想念的其他东西?
来自man fopen(重点是我的)
读写可以以任何顺序混合在读/写流上。请注意,除非输入操作遇到文件结尾,否则ANSI C要求在输出和输入之间插入文件定位功能。(如果不满足此条件,则允许读操作返回除最近的写操作以外的结果。)因此,将fseek(3)或fgetpos(3 )在此类流上进行读写操作之间的操作。此操作可能是明显的禁止操作(如在fseek(...,0L,SEEK_CUR)中因其同步副作用而被调用)。
这“确实有时需要”是你经验丰富,为什么什么fseek(fp,0,SEEK_CUR);
或fflush(fp);
之后fputs()
解决问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句