如何读取,加密和覆盖文本文件

时间:2016-09-22 19:52:00

标签: c

我只想获取文件的内容并将其加密到同一个文件中。

我知道它不是最有效的加密形式,但我只是在玩它以查看代码如何读取文件。

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;
}

1 个答案:

答案 0 :(得分: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);
}