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

标签 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
          }

我的语法有问题

最佳答案

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);
    }
}

关于c - 如何在从另一个文件复制时编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31105735/

相关文章:

java - protobuf RPC结构(嵌入式ARM)

java - 我试图通过蓝牙发送数据,但 Serial.available() 总是返回 0

c - 在 printf 语句中使用 %x 打印整数数据类型的值

linux - 当我在启用 ufw 的情况下使用 iptables 阻止特定用户访问 Internet 时出现问题

linux - 有没有办法创建虚拟 Linux MTD 设备,模拟一个用于实验

java - C++ 中的 typedef 关键字是否有 Java 等效项或方法?

c - AVX2 1x mm256i 32 位到 2x mm256i 64 位

linux - phpmyadmin index.php 文件不见了

c - 为什么从 bash 脚本调用超时程序会导致 tcsetattr 挂起?

linux - 如何以 root 用户身份在命令行中通过 RTSP 使用 VLC 流式传输视频?