1

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

当我这样做时,我的程序应该生成一个名为:“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);
}
4

1 回答 1

4

好的,我认为这会有所帮助:

#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在程序末尾添加关闭文件句柄的语句。固定的!

于 2013-06-01T02:50:42.767 回答