C - Better method for replacing

2019-08-07 04:08发布

问题:

I'm looking to replace words from a file where words.txt contains "banana test apple" would output -> "banana Replaced! apple" The words it would be looking to replace would come as an argument to stdin ("test" in this case)

Not sure where my code is going wrong, and I'm also wondering if there's a better way to do it than get getchar() function, as I find it confusing to work with, and annoying as you cannot backup characters.

Any suggestions? Thanks

    $ ./a.exe test < words.txt


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

    int main(int argc, char** argv) { 
        int c = getchar();    
        int counter = 0;


        int i,index;
        for (i = 1; i < argc; i++){
            for (index = 0; index < strlen(argv[i]); index++){
                while (c == argv[i][index]){
                    counter++;
                    c = getchar();
                    index++;
                    if (counter == strlen(argv[i])){
                        printf("Replaced!");
                    }
                }
                printf("%c ",c);
                c = getchar();
                counter = 0;
            }
        }
        return (0);
    }

回答1:

I would do it as follows :

  1. read all the file into a buffer using fgets
  2. looking for the key work (test) using strstr
  3. replace it with your new string using strncpy
  4. write to file (or output to stdout) whatever you want to do


回答2:

You could use scanf to read in a word at a time:

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

int main(int argc, char *argv[])
{
    char wordbuffer[100];
    while (scanf("%99s", wordbuffer) == 1)
    {
        int replace = 0;
        for (int i = 1; i < argc && !replace; i++)
            if (strcmp(wordbuffer, argv[i]) == 0)
                replace = 1;

        if (replace)
            printf("Replaced! ");
        else
            printf("%s ", wordbuffer);
    }
}

If you are using a modern system that compliant with the latest POSIX specification, you can take advantage of the m assignment-allocation character, and have the appropriate amount of space allocated for you, so that you don't have to use some arbitrary maximum number of characters.

int main(int argc, char *argv[])
{
    char *wordbuffer;
    while (scanf("%ms", &wordbuffer) == 1)
    {
        int replace = 0;
        for (int i = 1; i < argc && !replace; i++)
            if (strcmp(wordbuffer, argv[i]) == 0)
                replace = 1;

        if (replace)
            printf("Replaced! ");
        else
            printf("%s ", wordbuffer);

        free(wordbuffer);
    }
}


标签: c file stdin