如何编写程序以使用命令行中指定的字符交换输入文件中的字符?

时间:2013-06-01 02:16:11

标签: c file

我正在尝试编写一个程序来交换我在命令行(命令行参数)上指定的字符和输入文本文件中的字符。第一个命令行参数是我想要更改的字符,第二个参数是我要用旧字符替换的字符,第三个参数是输入文件。

当我这样做时,我的程序应生成一个名为“translation.txt”的输出文件。我知道我的程序的问题在于“if”语句/ fprintf语句,但我不知道如何解决这个问题。我正在考虑单独读取输入文件中的每个字符,从那里,我想使用“if”语句来确定是否替换字符。

void replace_character(int arg_list, char *arguments[])
{
   FILE *input, *output;

   input = fopen(arguments[3], "r");
   output = fopen("translation.txt", "w");

   if (input == NULL)
   {
      perror("Error: file cannot be opened\n");
   }

   for (int i = 0; i != EOF; i++)
   {
      if (input[i] == arguments[1])
      {
         fprintf(output, "%c\n", arguments[2]);
      }
      else
      {
         fprintf(output, "%c\n", arguments[1]);
      }
   }
}

int main(int argc, char *argv[])
{
   if (argc < 5)
   {
      perror("Error!\n");
   }

   replace_character(argc, argv);
}

1 个答案:

答案 0 :(得分:3)

好的,我认为这可以提供帮助:

#include <stdio.h>

int main(int argc, char** argv)
{
    if (argc < 4) return -1; /* quit if argument list not there */

    FILE* handle = fopen(argv[3], "r+"); /* open the file for reading and updating */

    if (handle == NULL) return -1; /* if file not found quit */

    char current_char = 0;
    char to_replace = argv[1][0]; /* get the character to be replaced */
    char replacement = argv[2][0]; /* get the replacing character */

    while ((current_char  = fgetc(handle)) != EOF) /* while it's not the end-of-file */
    {                                              /*   read a character at a time */

        if (current_char == to_replace) /* if we've found our character */
        {
            fseek(handle, ftell(handle) - 1, SEEK_SET); /* set the position of the stream
                                                           one character back, this is done by
                                                           getting the current position using     
                                                           ftell, subtracting one from it and 
                                                           using fseek to set a new position */

            fprintf(handle, "%c", replacement); /* write the new character at the new position */
        }
    }

    fclose(handle); /* it's important to close the file_handle 
                       when you're done with it to avoid memory leaks */

    return 0;
}

如果将输入指定为第一个参数,它将寻找要替换的字符,然后将其替换为replacement中存储的字符。尝试一下,如果它不起作用,请告诉我。我这样运行:

./a.out l a input_trans.txt

我的文件只有字符串'Hello,World!'。在运行之后,它变成了'Heaao,Worad!'。

阅读ftellfseek,因为它们是您需要做的事情的关键。

编辑:忘记添加fclose语句,该语句在程序结束时关闭文件句柄。固定!