[英]Scanning in from a text file
對於我的解密程序,我必須能夠從文本文件的最下面的替代表的后面掃描替代表,該文本文件具有加密的文本。 我必須使用該替換表來解密消息。 因此,現在我相信最好的方法是先掃描替換表,然后將兩列都存儲到2個不同的數組中,然后在最后掃描加密的消息。 但是,我不知道該怎么做。
我知道無論如何替換表將不再是62行(26 + 26 + 10)。 但是,加密的消息可以具有所需的任意多行。
加密的文本文件(projectinput.txt)通常如下所示:
a m
b n
etc...
z q
A P
B O
etc...
Z X
0 5
1 4
etc...
9 0
Ekrmov 04320
SDFVSDFV
當前的解密代碼:
#include <stdio.h>
char input[256];
char encrypted[256];
char line[100];
int c;
int j;
int main(){
FILE *file1=fopen("projectoutput.txt", "r");
FILE *file2=fopen("projectinput.txt", "w");
while(fgets(line,100,file1)!=NULL){
sscanf(line, "%c %c", input, encrypted);
fprintf(file2, "%c %c\n", input[j], encrypted[j]);
}
while((c=fgetc(file1))!=EOF){
int i=0;
while(encrypted[i]!=c){
i++;
}
fputc(input[i], file2);
}
return 0;
}
我剛剛更新了代碼,包含fgets的while循環能夠將替換表存儲到2個數組中,但是,它還將加密消息也存儲在底部。 我想停止while循環讀取超過62行的內容,該怎么辦?
for(i = 0; i < 62: i++){
input[i] = fgetc(file1);
fgetc(file1);
encrypted[i] = fgetc(file1);
fgetc(file1);
}
編輯:試試這個
char *buff;
char *decoded;
long file_Size;
fseek(file1, 0, SEEK_END);
file_Size = ftell(file1);
fseek(file1, 0, SEEK_SET);
buff = malloc(file_Size * sizeof(char));
decoded = malloc((file_Size - 62 * 4) * sizeof(char));
//writing all text file to buff array. It is faster and the array is easier to
//manipulate
fread(buff, sizeof(unsigned char), file_Size, file1);
j = 0;
for(i = 0; i < 62; i++){
input[i] = buff[j];
encrypted[i] = buff[j + 2];
j += 4;
}
//move encrypted message to decoded array
memmove(decoded, &buff[62 * 4], file_Size - 62 * 4);
//decoding process
for(i = 0; i < file_Size - 62 * 4; i++){
for(j = 0; j < 62; j++){
if(decoded[i] == '\n' || decoded[i] == ' '){break;}
if(decoded[i] == input[j]){decoded[i] = encrypted[j]; break;}
}
}
將decoded
寫入file2並
free(decoded);
free(buff);
瓦爾特
您可以通過兩種方式執行此操作:
fgets()
。 對於每一行,使用strtok
按空格標記進行分割: http : strtok
並將每個字符分配給適當的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.