c/c++语言开发共享试图在C中查找并替换文件中的字符串

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 %sn",str,replace); } } fclose(fp); } int main(int argc, char **argv) { char* file= "text.txt"; replaceString(file,"is","was"); printFile(file); return 0; } 

伙计我是文件操作的新手,试图找到并替换另一个字符串。 请帮忙! 我试图以“rt”模式打开文件。 在一些示例代码中看到了这一点。 不确定模式。 我猜我需要使用temp.txt文件来做到这一点! 它可以在一个文件中完成而不使用任何其他文件??

    以下是算法中的一些错误。

    写这样的替换并不像你想象的那么简单。 我可以尝试帮助你,但如果你只是想学习使用文件并且仍然不能完全熟悉字符串,那么它可能会有点过头了。

    如果你有足够的内存来一次读取整个文件(如果BUFFER大于文件大小),那么在单个文件中进行替换很容易,但是如果不是特别是在你的情况下, replacestr长,则非常棘手。

    此代码替换了所有“orig”文本的出现。 您可以根据需要进行修改:

     #include  #include  #include  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 = ''; strcpy(buf, tmpbuf); free(tmpbuf); } int main(int argc, char **argv) { char str[] = "malatya istanbul madrid newyork"; replaceString(str, "malatya", "ankara"); printf("%sn", str); replaceString(str, "madrid", "tokyo"); printf("%sn", str); return 0; } 

    我会看一下使用缓冲区并对此进行处理。

     #include  #include  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; } 

    "rt"模式仅供读取。 使用"r+"模式。 这将打开读写文件。

    需要了解更多c/c++开发分享试图在C中查找并替换文件中的字符串,也可以关注C/ C++技术分享栏目—计算机技术网(www.ctvol.com)!

      以上就是c/c++开发分享试图在C中查找并替换文件中的字符串相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/978850.html

      (0)
      上一篇 2021年12月12日
      下一篇 2021年12月12日

      精彩推荐