我正在尝试编写一个程序来交换我将在命令行(命令行参数)上指定的字符与输入文本文件中的字符。第一个命令行参数是我要更改的字符,第二个参数是我要替换旧字符的字符,第三个参数是输入文件。
当我这样做时,我的程序应该生成一个名为“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);
}
最佳答案
好的,我认为这可以帮助:
#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!”。
继续阅读 ftell和 fseek ,因为它们是您需要执行的操作的关键。
编辑:忘记添加一个 fclose
语句来关闭程序末尾的文件句柄。已修复!
关于c - 如何编写程序将输入文件中的字符与命令行中指定的字符交换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868439/