我遇到了我的代碼問題。我有循環根據用戶輸入的密鑰對短語進行解密/加密。該程序通過命令行通過執行運行:文件輸入和輸出,循環創建新行
./program [-d] [-e] key sourcefile destinationfile
的〔-d]和[-e]手段解密或加密,用戶只能指定一個選項。該程序從源文件中獲取文本短語,對其進行操作,然後將新短語寫入新文件。然而,我注意到由於某種原因,我的for循環分割了這個短語,並根據關鍵在新文件中搞砸了這個序列。看到結果我得到下面當我加密:
key source dest
2 Testing1234567890ABCDEF Tsig24680BDFetn13579ACE correct
3 Testing1234567890ABCDEF Ttg369BEei1470CFsn258AD correct
4 Testing1234567890ABCDEF Ti260Den37AEsg47BFt159C correct
5 Testing1234567890ABCDEF Tn49Deg50Es16AFt27B incorrect
i38C
6 Testing1234567890ABCDEF Tg6Be17Cs28Dt39Ei40Fn5A correct
7 Testing1234567890ABCDEF T18Ee29Fs30 incorrect
t4Ai5Bn6Cg7D
8 Testing1234567890ABCDEF T20e3As4Bt5Ci6Dn7Eg8F19 correct
9 Testing1234567890ABCDEF T3be4Cs5Dt6Ei7Fn8
g9102A incorrect
10 Testing1234567890ABCDEF T4De5Es6Ft7
i8n9g01A2B3C incorrect
通知了如何使用5,7,9,和10分裂短語上兩行呢?那不應該發生,我甚至沒有循環中的換行符。我無法弄清楚造成這種情況的原因。
我下面的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 100
int main (int argc, char* argv[ ]) {
FILE* sourcefile;
FILE* destfile;
int i, j, filesize, key;
int pos = 0;
char phrase[ BUFFER_SIZE ];
char* newPhrase;
/* if user types -d or -e continue */
if ((argc == 5 && (strcmp (argv[ 1 ], "-d") == 0)) || (argc == 5 && (strcmp (argv[ 1 ], "-d") == 0))) {
/* exit if key is not an int */
key = atoi (argv[ 2 ]);
if (key < 1) {
perror ("Error: key is not a valid int");
exit (EXIT_FAILURE);
}
/* open source & destination files */
sourcefile = fopen (argv[ 3 ], "r");
/* display error message if source file does not exist */
if (sourcefile == NULL) {
perror ("");
exit (EXIT_FAILURE);
}
destfile = fopen (argv[ 4 ], "w");
/* extract the text in the source file */
fgets (phrase, BUFFER_SIZE, sourcefile);
fseek (sourcefile, 0, SEEK_END);
filesize = ftell (sourcefile);
/* allocate memory for new string that will go in destination file */
newPhrase = (char*) malloc (filesize);
/* decrypt */
if (strcmp (argv[ 1 ], "-d") == 0) {
for (i = 0; i < key; i++) {
for (j = i; j < strlen(phrase); j += key)
newPhrase[ j ] = phrase[ pos++ ];
}
}
/* encrypt */
else {
for (i = 0; i < key; i++) {
for (j = i; j < strlen(phrase); j += key)
newPhrase[ pos++ ] = phrase[ j ];
}
}
/* write new phrase to file, close files */
fputs(newPhrase, destfile);
fclose (sourcefile);
fclose (destfile);
}
return 0;
}
使用調試器!問,如果你有一個具體的問題。 「這是我的代碼,爲我找到bug」不是一個好問題。 – JeffRSon
Offtopic:你沒有釋放'newPhrase' – 2013-11-24 16:30:14
你並沒有將'newPhrase'清零,在'fputs'調用之前嘗試'newPhrase [pos ++] ='\ 0'' – 2013-11-24 16:35:03