我想加密此文件,但输出丢失

时间:2018-09-13 02:49:03

标签: c++ encryption

执行以下代码后,我的out.txt似乎丢失了,我不知道该怎么办。

void Cripto::cipher(string path, byte key){
  ifstream file;

  file.open(path);
  file.seekg(0, file.end);
  long size = file.tellg();
  file.seekg(0);

  byte * characters = new byte[size];
  setCharacters(characters);
  file.read(characters, size);

  for(int i = 0; i < size; i++){
      characters[i] += getKey();
  }

  ofstream outfile("out.txt");
  outfile.write(characters, size);
}

1 个答案:

答案 0 :(得分:2)

您可以采取的措施来解决问题。

  1. 如果您使用的是POSIX系统,请使用getcwd来检索当前的工作目录并将其打印到终端上。这将使您了解程序在哪里尝试打开文件。
  2. 确保文件已成功打开。
  3. 不要以为从输入文件中读取数据是成功的。捕获成功读取并使用的字符数。

void Cripto::cipher(string path, byte key)
{
   // Print current working directory.
   char cwd[1000];
   getcwd(cwd, 1000);
   std::cout << "Current working directory: " << cwd << std::endl;

   ifstream file;
   file.open(path);
   if ( !file )
   {
      // Problem opening the file.
      // Throw an exception and get out of the function.
      throw std::runtime_error("Unable to open file for reading from");
   }

   file.seekg(0, file.end);
   long size = file.tellg();
   file.seekg(0);

   byte * characters = new byte[size];
   setCharacters(characters);
   long n = file.gcount();

   // Only n characters were read.
   if ( n != size )
   {
      // Print a warning message.
   }

   // Encrypt only the number of characters that were read.
   if ( n != size )
   {
      // Print a warning message.
   }

   // Encrypt only the number of characters were read.
   for(int i = 0; i < n; i++){
      characters[i] += getKey();
   }

   ofstream outfile("out.txt");
   if ( !outfile )
   {
      // Problem opening the file.
      // Throw an exception and get out of the function.
      throw std::runtime_error("Unable to open file for writing to");
   }

   // Write n characters, not size.
   outfile.write(characters, n);
}