您的位置:首页 > 其它

文件字符串匹配替换 2011.11.10

2011-11-10 13:25 190 查看
test.txt:

abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz

abcdefghijklmnopqrstuvwxyz

#include   <stdio.h>

int   main()
{
FILE   *in   =   fopen( "test.txt",   "r ");
FILE   *out   =   fopen( "test1.txt",   "w ");

const   char   *from   =   "mno ";                               /*   要替换

的源串   */
const   char   *to   =   "1234";             /*   目标串   */
const   char   *pFrom   =   from;                               /*   匹配指

针   */

char   c;
while   ((c   =   getc(in))   !=   EOF)
{
if   (*pFrom   ==   c)                                   /*   判断(

1)   */
{
++pFrom;
if   (*pFrom   ==   '\0 ')
{
fprintf(out,   "%s ",   to);
pFrom   =   from;
}
}
else   /*   否则若不匹配,则   */
{
if   (pFrom   !=   from)   /*   若匹配指针不处于替换串首字符

位置,说明前面已经匹配了一部分,则   */
{
const   char   *pPushBack;
for   (pPushBack   =   from;   pPushBack   !=

pFrom;   ++pPushBack)
{
putc(*pPushBack,   out);
}
pFrom   =   from;
}
putc(c,   out);
}
}

fclose(out);
fclose(in);
return   0;
}


test1.txt:

abcdefghijkl1234 pqrstuvwxyz

abcdefghijkl1234 pqrstuvwxyz

abcdefghijkl1234 pqrstuvwxyz

abcdefghijkl1234 pqrstuvwxyz

在某处看到,转来做笔记用……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: