我正在尝试制作一个解密程序,其中我有一个文件,其中包含需要替换的字符(replace.txt)。 Replace.txt的示例内容如下:
a X
b Y
c A
d C
e I
f K
g J
h L
i P
...等等。
现在,我尝试读入这些行并保存原始字符 (a) 和替换字符 (X),离开replace.txt 的第一行。但是,我只能读入替换字符,而无法将原始字符保存到数组中。
#include <string.h>
#include <stdio.h>
int main() {
FILE * file;
FILE * fileTwo;
file = fopen("in.txt","rt"); // This is the encrypted text file
fileTwo = fopen("replace.txt","rt");
char line[4];
char replaceChar[1];
char orginialChar[1];
while(fgets(line, 4, fileTwo) != NULL) {
strtok(line, " ");
printf("The line is: %s \n",line);
strcpy(originalChar, &line[0]); // Trying to get the "a"
strcpy(replaceChar, &line[2]); // Trying to get the "X"
printf("Original Char is: %s \n",originalChar);
printf("Replace Char is: %s \n",replaceChar);
}
return 0;
}
第一次运行的输出是:
The line is: a
Original Char is:
Replace Char is: X
此后它就完全崩溃了。我该如何解决这个问题?提前致谢!
最佳答案
我需要做的是将 fgets 和行数组的大小增加到 5 而不是 3,这样就可以添加新行和空字符,如果不这样做,文件将被完全错误地读取。
然后,我必须增加原始字符的大小并将字符数组替换为 [2],以允许添加空终止符。
关于c - 如何将文件行中的字符保存到字符数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42472406/