Home > other >  Replacing characters with other characters in C files
Replacing characters with other characters in C files

Time:02-06

I am attempting to write a program that takes in two files (or if not provided either file, uses stdin/stdout to replace a specified character array with another character array.

For example: if passed "--ax - td" then my program will replace every instance of 'a' with 't' and every 'x' with 'd'.

Here is what I am trying:

char *takeOut = "ax";
char *putIn = "td";

FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
int ch;

   for (int i=0; i<strlen(putIn); i  ) {

      while ((ch = getc(in)) != EOF) {
           if (ch == '\n') { // for stdout displaying without "%"
              putc('\n', out); 
              break;
           } else if (ch != takeOut[i]) {
              putc(ch, out);
           } else {
              putc((putIn[i]), out);
           }
       }
    }

The program ensures that the putIn and takeOut are of the same size, by the way.

The result is that only the first letter specified is replaced in every instance (in this case all "a's" are replaced with "t's". But no "x's" are replaced with "d's".

What am I doing wrong?

CodePudding user response:

well you set i to 0 and read the whole input. This looks for 'a'. All fine, then you hit EOF.

then you loop back and set i = 1 to look for 'x', BUT the files are still at EOF. you need to rewind the files. Or close and reopen

Much better tho is to invert the loops

   while ((ch = getc(in)) != EOF) {
         for(int i = 0; i< strlen(takeout); i  {
            if(ch == takeout(i)......
         }
   }

this is much more efficient as it only reads the file once

CodePudding user response:

I would redesign the loop as already stated. It makes more sense to read one character at a time then checking if it matches. One flaw I noticed in your code is you're complicating how you're performing the checks. I would simply check if there's a match on an inner for loop, if the match is found, replace and break out of the loop. Outside of the inner loop you can then write whatever was read prior in the case a match didn't occur.

    while ((ch = getc(in)) != EOF) {
        for(int x =0; x < strlen(putIn);  x){
            if(ch==takeOut[x]){
                putc(putIn[x], out);
                ch = 0;
                break;
            }
        }
        if(ch){
            putc(ch, out);
        }
    }

If a replacement occured, we set ch to 0 and there's no need to perform another write. If a replacement did not occur then put the original char into the outfile.

  •  Tags:  
  • Related