本文介绍了需要加密一个文件我有它所有写,但在阅读文件错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< stdio.h> 
#include< string.h>
#include< stdlib.h>

int encrypt_data(FILE *);

int main(void)
{
FILE * fp;
int return_code;

printf(请输入要加密的文件:);
char filename [200];
fgets(filename,200,stdin);
fp = fopen(filename,w +);

return_code = encrypt_data(fp);

return 0;
}
int encrypt_data(FILE * disk_fp)
{
int i;
unsigned long int file_size;
int key_length;
char * file_buff = NULL;

char key [] =12`3-vk0fn;

key_length = strlen(key);

fseek(disk_fp,0,SEEK_END);
file_size = ftell(disk_fp);

rewind(disk_fp);

file_buff = malloc(file_size);

如果(fread(file_buff,file_size,1,disk_fp)!= 1)
{
printf(读取文件中的错误);
return -1;
}

for(i = 0; i< file_size; i ++)
{
file_buff [i] = file_buff [i] ^ key [i%key_length] ;
}

rewind(disk_fp);

如果(fwrite(file_buff,file_size,1,disk_fp)!= 1)
{
printf(将加密数据写入文件\时出错)
return -1;
}
free(file_buff);
fclose(disk_fp);

return 0;
}

我要加密的文件是encrypt.txt,它只是一句废话,但是当我编译此代码然后./a.out它要求我的文件名我输入encrypt.txt我认为它可能只是想要的名称,但任何一种方式返回读取文件中的错误。 / p>

我认为我的fgets()fopen()是罪魁祸首,但我非常失去了如何解决它。



如果您可以在代码中找到错误,然后解释为什么会混乱的事情将会帮助我。非常感谢。

解决方案

删除文件名变量的双引号。并将其作为

  fp = fopen(filename,w +); 


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int encrypt_data(FILE *);

int main(void)
{
   FILE *fp;
   int return_code;

   printf("Please enter the file to be encrypted: ");
   char filename[200];
   fgets(filename, 200, stdin);
   fp=fopen("filename","w+");

   return_code = encrypt_data(fp);

   return 0;
}
int encrypt_data(FILE *disk_fp)
{
  int i;
  unsigned long int file_size;
  int key_length;
  char *file_buff = NULL;

  char key[] = "12`3-vk0fn";

  key_length = strlen(key);

  fseek(disk_fp, 0, SEEK_END);
  file_size = ftell(disk_fp);

  rewind(disk_fp);

  file_buff = malloc(file_size);

  if( fread(file_buff, file_size, 1, disk_fp) != 1)
  {
   printf("Error in reading file\n");
   return -1;
  }

  for( i=0; i<file_size; i++)
  {
   file_buff[i] = file_buff[i] ^ key[i%key_length];
  }

  rewind(disk_fp);

  if( fwrite(file_buff, file_size, 1, disk_fp) != 1)
  {
   printf("Error in writing encrypted data to file\n");
   return -1;
  }
  free(file_buff);
  fclose(disk_fp);

return 0;
}

The file I am trying to encrypt is "encrypt.txt" it is just a sentence of nonsense but when I compile this code and then ./a.out it asks me for the file name i enter encrypt.txt I thought it might just want the name but either way it returns "Error in reading file".

I think my fgets() fopen() is the culprit but I am very very lost in how to fix it.

If you could find the error in the code and then explain why it was messing things up it would help me in the future. Thanks a lot.

解决方案

Remove double quotes of the filename variable. And put it as

fp=fopen(filename,"w+");

这篇关于需要加密一个文件我有它所有写,但在阅读文件错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:04