c - 将文本文件输出到屏幕

标签 c

我需要制作一个“搜索和替换”程序。它不必在输入文件中进行更改,而只需在屏幕上进行更改。

示例:

file: foo pap ran bar foo. Nam foo!

replace:  foo >with> bar

output to screen: bar pap ran bar bar. Nam bar!`

有人知道我该怎么做吗?我是 C 新手。

最佳答案

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

long GetFileSize(FILE *fp){
    long fsize = 0;

    fseek(fp,0,SEEK_END);
    fsize = ftell(fp); 
    fseek(fp,0,SEEK_SET);//reset stream position!!

    return fsize;
}

int main(int argc, char **argv){
    char *file, *sword, *rword, *buff, *wp,*bp;
    int len;
    long fsize;
    FILE *inpFile;

    if(argc != 4){
        fprintf(stderr, "Usage:rep filePath originalWord replaceWord\n");
        exit(EXIT_FAILURE);
    }
    file  = argv[1];
    sword = argv[2];
    rword = argv[3];
    if(NULL==(inpFile=fopen(file, "rb"))){
        perror("Can't open file");
        exit(EXIT_FAILURE);
    }
    fsize = GetFileSize(inpFile);
    buff=(char*)malloc(sizeof(char)*fsize+1);
    fread(buff, sizeof(char), fsize, inpFile);//file all read into buff
    fclose(inpFile);
    buff[fsize]='\0';
    bp=buff;
    len = strlen(sword);
    while(NULL!=(wp=strstr(bp, sword))){
        while(bp != wp)
            putchar(*bp++);
        printf("%s",rword);
        bp+=len;
    }
    if(bp) printf("%s", bp);
    free(buff);
    return 0;
}

关于c - 将文本文件输出到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10133201/

相关文章:

c - C 中带索引的指针和数组

c - PIC18F25K80 通过 USART 发送字符串不起作用

c - 根据条件执行或跳过 ld.so.preload 共享库代码

c - 由于我是嵌入式编程的新手,所以我无法理解 "%s\xC2\xB0"是什么?我知道 %s 是字符串

c - 链表打印问题结构

c - free() 指针

Microsoft Windows 中的 CPU 设备驱动程序

c - exec() 输出重定向时的奇怪行为

c++ - 在 linux 中将 "plugins"放在哪里

内存分配后创建元数据页脚