C语言 尝试从 C 中的文件中查找和替换字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15054077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to find and replace a string from file in C
提问by Soumyajit Roy
void replaceString(char* file, char* str, char* replace)
{
FILE* fp = fopen(file,"rt");
char buffer[BUFFER];
while(fgets(buffer,BUFFER,fp)!=NULL)
{
char* s;
s=strstr(buffer,str);
if(s!=NULL)
{
strcpy(s,replace);
printf("%s is replaced by %s\n",str,replace);
}
}
fclose(fp);
}
int main(int argc, char **argv)
{
char* file= "text.txt";
replaceString(file,"is","was");
printFile(file);
return 0;
}
Guys I am new to file operations, trying to find and replace a string by another. please help! I am trying to open the file in "rt" mode. Saw this in some example code. Not sure about the mode. I am guessing that I need to use a temp.txt file to do that! Can it be done in a single file without using any other file??
伙计们,我是文件操作的新手,试图找到一个字符串并将其替换为另一个字符串。请帮忙!我正在尝试以“rt”模式打开文件。在一些示例代码中看到了这一点。不确定模式。我猜我需要使用 temp.txt 文件来做到这一点!可以在不使用任何其他文件的情况下在单个文件中完成吗??
回答by rabensky
Here are some of the errors in your algorithm.
以下是您算法中的一些错误。
You read and look atone BUFFER of chars at a time, with no overlap. What if
strappears between buffers? (i.e. the first part ofstris at the end of a buffer and the second part is at the start of the next buffer).You try to overwrite
strwithreplacedirectly in the buffer usingstrcpy. What if both strings are of different length? Ifreplaceis shorter thanstr, you'd still have the end ofstrthere and ifreplaceis longer, it will overwrite the text followingstrEven if they are the same length,
strcpyadds the final 0 char at the end of the copy (that's how they tell you where the string ended). you DEFINITIVELY don't want that. Maybestrncpyis a better suggestion here, although it will still not work if both strings aren't the same length.You replace the strings in the buffer but do nothing with the "corrected" buffer! The buffer is not the file, the content of the file was COPIED into the buffer. So you changed the copy and then nothing. The file will not change. You need to write your changes into a file, preferably a different one.
您一次阅读并查看一个 BUFFER 字符,没有重叠。如果
str出现在缓冲区之间怎么办?(即第一部分str在缓冲区的末尾,第二部分在下一个缓冲区的开头)。您尝试
str使用replace直接在缓冲区中覆盖strcpy。如果两个字符串的长度不同怎么办?如果replace短于str,您仍然会在str那里结束,如果replace更长,它将覆盖以下文本str即使它们的长度相同,也会在
strcpy副本的末尾添加最后一个 0 字符(这就是它们告诉您字符串在哪里结束的方式)。你绝对不想要那个。也许strncpy这里是一个更好的建议,尽管如果两个字符串的长度不同,它仍然不起作用。您替换缓冲区中的字符串,但对“更正”的缓冲区不做任何处理!缓冲区不是文件,文件的内容被复制到缓冲区中。所以你改变了副本,然后什么都没有。文件不会改变。您需要将更改写入一个文件,最好是另一个文件。
Writing such a replace isn't as trivial as you might think. I may try and help you, but it might be a bit over your head if you're just trying to learn working with files and are still not fully comfortable with strings.
编写这样的替换并不像您想象的那么简单。我可能会尝试帮助你,但如果你只是想学习使用文件并且仍然不完全熟悉字符串,那么它可能会有点超出你的头脑。
Doing the replace in a single file is easy if you have enough memory to read the entire file at once (if BUFFERis larger than the file size), but very tricky if not especially in your case where replaceis longer than str.
如果您有足够的内存来一次读取整个文件(如果BUFFER大于文件大小),则在单个文件中进行替换很容易,但如果不是,则非常棘手,尤其是在replace长度超过str.
回答by tyilmaz
This code replaces all occurences of 'orig' text. You can modify as your needing:
此代码替换所有出现的 'orig' 文本。您可以根据需要进行修改:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void
replaceAllString(char *buf, const char *orig, const char *replace)
{
int olen, rlen;
char *s, *d;
char *tmpbuf;
if (!buf || !*buf || !orig || !*orig || !replace)
return;
tmpbuf = malloc(strlen(buf) + 1);
if (tmpbuf == NULL)
return;
olen = strlen(orig);
rlen = strlen(replace);
s = buf;
d = tmpbuf;
while (*s) {
if (strncmp(s, orig, olen) == 0) {
strcpy(d, replace);
s += olen;
d += rlen;
}
else
*d++ = *s++;
}
*d = '#include <stdio.h>
#include <string.h>
int main ( ) {
char buff[BUFSIZ]; // the input line
char newbuff[BUFSIZ]; // the results of any editing
char findme[] = "hello";
char replacewith[] = "world";
FILE *in, *out;
in = fopen( "file.txt", "r" );
out= fopen( "new.txt", "w" );
while ( fgets( buff, BUFSIZ, in ) != NULL ) {
if ( strstr( buff, findme ) != NULL ) {
// do 1 or more replacements
// the result should be placed in newbuff
// just watch you dont overflow newbuff...
} else {
// nothing to do - the input line is the output line
strcpy( newbuff, buff );
}
fputs( newbuff, out );
}
fclose( in );
fclose( out );
return 0;
}
';
strcpy(buf, tmpbuf);
free(tmpbuf);
}
int
main(int argc, char **argv)
{
char str[] = "malatya istanbul madrid newyork";
replaceString(str, "malatya", "ankara");
printf("%s\n", str);
replaceString(str, "madrid", "tokyo");
printf("%s\n", str);
return 0;
}
回答by Mohsin
"rt"mode is for read only. Use "r+"mode. That opens the file for both read and write.
"rt"模式是只读的。使用"r+"模式。这会打开文件以进行读取和写入。
回答by Niklas
I'd look at using a buffer and work on this.
我会考虑使用缓冲区并解决这个问题。
##代码##
