使用C中的cmd替换文件的单词

时间:2018-05-13 00:51:38

标签: c file cmd words

大家好我已经完成了一个用cmd代替另一个字母的程序。但我在试图取代整个单词时遇到了问题。我是新用的文件,所以我试图使用fgets和fputs,但我没有结果。 :/

这是我的代码:

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

//Function's prototypes
void atributos(int argc,char *argv[]);
void SustChar(char *argv[]);


//MAIN
int main(int argc, char *argv[]){


FILE *ptrf;
ptrf=fopen(argv[1],"r");
if(ptrf==NULL){
    printf("No se pudo abrir el archivo\n");
    exit(1);
}
else{
    fclose(ptrf);
    atributos(argc,argv);
}

    return 0;
}

//attributes


void atributos(int argc,char *argv[]){
    if(strcmp(argv[2],"S")==0)
    SustChar(argv);
}

//Replace words


void SustChar(char *argv[]){
    char c[80];

FILE *ptrf;
ptrf=fopen(argv[1],"r");
    FILE *ptrs;
    ptrs=fopen(argv[5],"w");

    while(!feof(ptrf)){    


    c=fgetc(ptrf);
    if(c==*argv[3])
        fputc(*argv[4],ptrs);
    else
        fputc(c,ptrs);    
}
    fclose(ptrs);
    fclose(ptrf);

}

我在cmd上使用的sintaxis是:.exeName origin.txt S oldword newword destiny.txt

Sintaxis' example

1 个答案:

答案 0 :(得分:0)

要比较整行,可以使用fgets读取一行并使用strcmp与第三个参数进行比较:

void SustChar(char *argv[]){
    char linebuf[80];
    FILE *ptrf;
    ptrf = fopen(argv[1],"r");
    FILE *ptrs;
    ptrs = fopen(argv[5],"w");
    // read line into a linebuf
    while(fgets(linebuf, 80, ptrf) != NULL){    
        linebuf[strlen(linebuf)-2] = '\0'; // remove newline character
        // if the line matches the third argument
        if (!strcmp(linebuf, argv[3])) {
            fputs(argv[4], ptrs);
        } else {
            fputs(linebuf, ptrs);    
        }
    }
    fclose(ptrs);
    fclose(ptrf);
}    

如果您对该行中的特定单词感兴趣,假设单词空格字符对单词进行了分隔,则可以使用strchr函数提取单词,然后将它们与第三个参数进行比较。

void SustChar(char *argv[]){
    char linebuf[80];
    FILE *ptrf;
    ptrf = fopen(argv[1],"r");
    FILE *ptrs;
    ptrs = fopen(argv[5],"w");
    // read one line into a linebuf
    while(fgets(linebuf, 80, ptrf) != NULL) {
        // remove newline character
        linebuf[strlen(linebuf)-2] = '\0';
        // get a pointer to the second word in the line
        char *secondword = strchr(strchr(linebuf, ' ') + 1, ' ');
        assert(secondword != NULL);
        // get length of the second word
        char *thirdword = strchr(secondword , ' ');
        size_t secondwordlen = thirdword == NULL ? strlen(secondword) : thirdword - secondword;
        // if the second word matches the third argument
        if (!memcmp(secondword , argv[3], secondwordlen)) {
            secondword[0] = '\0'; // remove second word from linebuf
            fputs(linebuf, ptrs); // print first word
            fputs(argv[3], ptrs); // print second word substituted by argv[3]
            fputs(thirdword, ptrs); // print the rest of the line
        } else {
            fputs(linebuf, ptrs);    
        }
    }
    fclose(ptrs);
    fclose(ptrf);
}