2012-03-18 66 views
0

對於我必須做的實驗,我需要創建一個程序,它將從文本文件中獲取一個簡單的字符串,並使用一個鍵進行加密 - 一個介於0和255之間的數字。它將讀取將該文件轉換爲數組,並通過將每個字節與密鑰異或來將該數組加密(或解密)爲另一個數組。最後,它將修改後的數組寫入第二個文件。加密一個簡單的數組

我主要得到它 - 我在下面編譯得很好。但是,它不會將任何內容複製到第二個文件。幫幫我!

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define CRYPT(a, b) (a^b) 

int main(int argc, char *argv[]) 
{ 
    FILE *fp1, *fp2; 
    int a[100], b, key; 
    int i = 0; 

    // opens file containing string to be encrypted 
    if((fp1 = fopen(argv[2], "rb")) == NULL) 
    { 
      printf("Error - could not open file or file does not exist\n"); 
      return; 
    } 

    // opens file encrypted string will be saved to 
    fp2 = fopen(argv[3], "wb"); 

    // converts string to integer 
    key = atoi(argv[1]); 

    while(fread(a, sizeof(a), 100, fp1)) 
    { 
      while (i != '\0'); 
      { 
        b = CRYPT(a[i], key); 
        fwrite(&b, sizeof(a), 1, fp2); 
        i++; 
      } 
    } 


    return 0; 

}

回答

0

我認爲問題就出在這裏 -

while (i != '\0'); 

要初始化i爲0,並且在while循環要檢查我是否不等於NULL。整數值NULL\0爲0.因此,該表達式爲false,並且您的循環從不被執行。

還在此while循環結束時刪除多餘的分號。

reference -

爲size_t的fread(無效* PTR,爲size_t大小,爲size_t計數,FILE *流);

讀取的計數元件的陣列,每一個的尺寸爲大小字節,從由PTR指定的,並將它們存儲在存儲器的塊。 流的位置指示符超前讀取的總字節數。 成功讀取的字節總數量是(size * count)。

所以你還需要你的fread功能改變這一點 - 同樣

fread(a, sizeof(int), 100, fp1) 

,你還需要改變你的fwrite -

fwrite(&b, sizeof(int), 1, fp2); 

編輯的代碼應該是這個樣子 -

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define CRYPT(a, b) (a^b) 

int main(int argc, char *argv[]) 
{ 
    FILE *fp1, *fp2; 
    int a[100], b, key; 
    int i = 0; 
    int data_read = 0; 

    // opens file containing string to be encrypted 
    if((fp1 = fopen(argv[2], "rb")) == NULL) 
    { 
      printf("Error - could not open file or file does not exist\n"); 
      return; 
    } 

    // opens file encrypted string will be saved to 
    fp2 = fopen(argv[3], "wb"); 

    // converts string to integer 
    key = atoi(argv[1]); 

    while((data_read = fread(a, sizeof(int), 100, fp1)) > 0) 
    { 
      while(i < data_read) 
      { 
        b = CRYPT(a[i], key); 
        fwrite(&b, sizeof(int), 1, fp2); 
        i++; 
      } 

      i=0; 
    } 

    return 0; 
} 
+0

啊,我把它改成'while(!feof(fp1));',但這仍然沒有任何幫助。 – 2012-03-18 06:53:19

+2

另外,在該行末尾的額外分號並沒有幫助... – 2012-03-18 06:54:46

+0

@ ThomasPadron-McCarthy:好! – 2012-03-18 06:55:51

0

您的代碼存在一些嚴重缺陷。

首先,在整數數組a中存在緩衝區溢出(即,可以將超過100個整數讀入a中)。

正如Thomas McCarthy在你的while循環結尾創建了一個空語句的分號 - 刪除它。

此外,您正在爲每個角色寫入sizeof(a)或100個整數到fp2。