我有一个奇怪的问题:以下代码用于实现xor加密,但我无法调试为什么没有写入磁盘。我在想我正在使用fseek
或fputc
。以下是我的问题的一个工作示例。我做错了什么?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *key, *data;
char keyf[] = "/sdcard/key";
char dataf[128];
int c0, c1, c2;
long int i;
key = fopen(keyf, "r+");
if (key == NULL) {
printf("%s missing\n", keyf);
exit(1);
}
printf("data file:\n");
i = 0;
while ((c0 = getc(stdin)) != '\n' &&
i < 128)
dataf[i++] = (char)c0;
data = fopen(dataf, "r");
if (data == NULL) {
printf("%s missing\n", dataf);
exit(2);
}
i = 0;
while ((c0 = fgetc(key)) != EOF &&
(c1 = fgetc(data)) != EOF) {
while (!c0) c0 = fgetc(key);
c2 = c0 ^ c1;
fseek(data, i++, SEEK_SET);
fputc(c2, data);
printf("%c", c2);
}
fflush(data);
fclose(key);
fclose(data);
return 0;
}
答案 0 :(得分:0)
您已将data
打开为只读状态。您将需要打开它进行读写,并且您不需要截断,因此您需要模式"r+"
,这将打开文件以便读取/写入两个开头的位置..当你从文件中读取,文件指针将递增,因此要回写刚读过的字符,您还需要使用fseek()
寻找回去。
Here is a link to the fopen man page which describes access modes.
This is the fseek man page which will describe how to move your file position around.