如何在从另一个文件复制时编辑文件

时间:2015-06-28 23:11:55

标签: c linux

如何在从其他文件复制文件时编辑文件

source = fopen("sourceFile.txt", "r");
          if( source == NULL ) 
            {
                printf("Error in doStepOneAndTwo, can't open file source \n");
                return USERERR;
            }

target = fopen("targetFile.txt", "w");
          if( target == NULL ) 
            {
                fclose(source);
                printf("Error in doStepOneAndTwo, can't open file target %s \n",str);
                return USERERR;
            }

while( ( ch = fgetc(source) ) != EOF ) 
          {
              fputc(ch, target);
              //Here I need to check if ch == "blah" change it to "twoBlah" and save twoBlah to targetFile.txt instead of blah
          }

我的语法有问题

1 个答案:

答案 0 :(得分:1)

const char *search_word = "blah";
const char *replace_word = "twoBlah";
const char *p = search_word;

while(1){
    ch = fgetc(source);
    if(*p == ch){
        ++p;
        if(!*p){//match!
            fprintf(target, "%s", replace_word);
            p = search_word;
        }
    } else {
        if(p != search_word){
            const char *temp = search_word;
            while(temp != p)
                fputc(*temp++, target);
            p = search_word;
        }
        if(ch == EOF)
            break;
        fputc(ch, target);
    }
}