我只想获取文件的内容并在同一个文件上加密。
我知道这不是最有效的加密形式,但我只是想看看代码如何读取文件。
Hello.txt 有“abcdefg”。
但是当我通过它运行代码时,没有任何变化。
我做错了什么?
#include<stdio.h>
int main(){
FILE *fp1=NULL;
char ch;
fp1=fopen("C:\\Hello.txt","r+");
if(fp1==NULL)
{
printf("fp1 NULL!\n");
}
while(1){
ch=fgetc(fp1);
if(ch==EOF){
printf("End of File\n");
break;
}
else{
ch=ch*10;
fputc(ch,fp1);
}
}
fclose(fp1);
return 0;
}
最佳答案
Joachim Pileborg 已经使用评论来暗示您所犯的错误,让我不那么微妙:
#include <stdio.h>
#include <stdlib.h>
// Cesar cipher
int main(int argc, char **argv)
{
FILE *fp1 = NULL;
// we need an int to check for EOF
int ch;
fp1 = fopen("Hello.txt", "r+");
if (fp1 == NULL) {
fprintf(stderr, "fp1 NULL!\n");
exit(EXIT_FAILURE);
}
while (1) {
// get character (fgetc returns an int)
ch = fgetc(fp1);
if (ch == EOF) {
printf("End of File\n");
break;
} else {
// Set file-pointer back to the position of
// the character just read (it is a bit more
// complicated internally and works only for one)
ungetc(ch, fp1);
// do decryption
if (argc == 2 && *argv[1] == 'd') {
ch = ch - 3;
}
// do encrytion (default)
else if (argc == 1 || (argc == 2 && *argv[1] == 'e')) {
ch = ch + 3;
}
// print character (fputc takes an int)
fputc(ch, fp1);
}
}
fclose(fp1);
exit(EXIT_SUCCESS);
}
关于c - 如何读取、加密和覆盖文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647772/