c++文件加密問題記錄與解決


(第一篇博客,希望大家多多支持!還是初學者,若有問題或更好的見解請在評論區指出,歡迎交流!)

一、問題描述

  Write an encryption program that reads from cin (a file)and writes the encoded characters to cout (a file).

  You might use this simple encryption scheme: the encrypted form of a character c is c^key[i], where key is a string passed as a command-line argument. The program uses the characters in key in a cyclic manner until all the input has been read. Re-encrypting encoded text with the same key produces the original text. If no key (or a null string) is passed, then no encrption is done.

二、問題解決

  1.thinking

    創建三個文件:in.txt(用於讀入)、out.txt(加密結果存儲)、original.txt(解密結果存儲)。

    讀入文件,進行后續加密解密操作;若讀入失敗,進行異常處理。

  2.important

    ①.了解c++的位運算(此處主要為 ^ 異或運算)

    ②.關於文件的一些處理

  3.process

    ①.關於 異或 運算

      

      可以看出,異或運算返回值是int,而char ^ int實際對char進行了隱式類型轉換。

      另外,我們需要以char類型從in.txt文件中讀入,以int類型從out.txt中讀入。

      異或運算有一些特殊用途:1.一個數異或兩次是本身。2.一個數與0異或會保留原值(1001 1001 ^ 0000 0000 -> 1001 1001)

    ②.關於文件的讀入和EOF

      關於EOF的詳細解釋:https://www.cnblogs.com/dolphin0520/archive/2011/10/13/2210459.html

      

 

      在文件讀入時,每次讀入之后都應判斷是否讀到EOF。當然寫法根據具體情況而定。在此題中,若將讀入寫入循環體,判斷條件為while(!f_in.eof())會出現不可預測的問題,即使文件已經讀完,但循環不會終止!

 

  4.result

      分享源碼

 

 1 #include<iostream>
 2 #include<fstream>
 3 #include<cstring>
 4 
 5 using namespace std;
 6 
 7 int main(int argc,char** argv)
 8 {
 9     ifstream fin("in.txt");
10     if (!fin.is_open()) {
11         cout << "Can't open file \"in.txt\"";
12         return -1;
13     }
14 
15     fstream fout("out.txt");
16     if (!fout.is_open()) {  
17         cout << "Can't open file \"out.txt\"";
18         return -1;
19     }
20 
21     if(strlen(argv[1]) == 0){  //若沒receive到命令行參數,則不進行加密解密
22         string temp;
23         cout<<"No key . No encryption ."<<endl;
24         while(fin>>temp){
25             fout<<temp;
26         }
27         return 0;
28     }
29 
30     char temp;
31     int i = 0;
32 
33     while (fin.get(temp))    //加密運算
34     {
35         fout << (temp ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])]) << ' ';
36         i++;
37     }
38 
39     fin.close();
40     fout.close();
41 
42     cout << "Encryption has done ." << endl
43         << "Now begin re-encrypting ." << endl;
44 
45     ifstream f_in("out.txt");
46     if (!f_in.is_open()) {
47         cout << "Can't open file \"out.txt\"";
48         return -1;
49     }
50 
51     ofstream f_out("original.txt");
52     if (!f_out.is_open()) {
53         cout << "Can't open file \"original.txt\"";
54         return -1;
55     }
56 
57     i = 0;
58     int temp_1;
59     while (f_in >> temp_1) {  //解密運算,此處需要進行強制類型轉換輸出字符
60         f_out << char((temp_1 ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])]));
61         i++;
62     }
63 
64     cout << "Re-encryption has done." << endl;
65     return 0;
66 }

 

 

 

    

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM