Closed. This question is
off-topic。它当前不接受答案。
想改善这个问题吗?
Update the question,因此它是
on-topic,用于堆栈溢出。
6个月前关闭。
我进行了文件加密,但是只执行了第一部分代码,我无法弄清楚为什么下一部分没有运行,也许我错过了一些东西,可以帮助我解决问题。
int main() {
char exe[20] = "encrypt1.vr";
char txt[20] = "encrypt2.vr";
char jpg[20] = "encrypt3.vr";
FILE *fileptr, *files, *filed, *dskfileptr, *dskfiles;
int recode, decode;
int i; //used to index through file buffer
unsigned long int file_s; //holds number of bytes in file
int keylen; //holds length of key
char *filebuff = NULL;
char key[] = "ABCDEF";
keylen = strlen(key);
char fname[30] = "1.exe";
char name[40] = "2.txt";
char named[50] = "3.jpg";
rename(fname, exe);
rename(name, txt);
rename(named, jpg);
fileptr = fopen(exe, "rb+");
if (fileptr == NULL) {
printf("Failed to open file exe.\n");
return -1;
} else
fprintf(fileptr, "text\n");
fclose(fileptr);
system("pause");
return 0;
fileptr = fopen(exe, "rb+");
fseek(dskfileptr, 0, SEEK_END); //moves file pointer to end of file
file_s = ftell(dskfileptr); //get current file pointer location
//which will be the size of the file
rewind(dskfileptr); //in bytes
filebuff = malloc(file_s);
//read file bytes into RAM filebuff (which is just an array of chars)
if (fread(filebuff, file_s, 1, dskfileptr) != 1)
printf("Error in reading file.\n");
return -1;
for (i = 0; i < file_s; i++) //look through each byte of filebuff
filebuff[i] = filebuff[i] ^ key[i % keylen];
rewind(dskfileptr); //move file pointer back to the beginning
//of the file
//write encrypted bytes (in filebuff) back to disk file
if (fwrite(filebuff, file_s, 1, dskfileptr) != 1)
printf("Error in writing encrypted data to file.\n");
system("pause");
return -1;
free(filebuff); //returning RAM memory back to system
fclose(dskfileptr);
上面的代码有效
/\ /\ /\
WORK
DON'T WORK
\/ \/ \/
The code below does not work
files = fopen(txt, "rb+");
if (files == NULL) {
printf("Failed to open file txt.\n");
return -1;
} else
fprintf(files,"text\n");
fclose(files);
system("pause");
files = fopen(txt, "rb+");
fseek(files, 0, SEEK_END); //moves file pointer to end of file
file_s = ftell(files); //get current file pointer location
//which will be the size of the file
rewind(files); //in bytes
filebuff = malloc(file_s);
//read file bytes into RAM filebuff (which is just an array of chars)
if (fread(filebuff, file_s, 1, files) != 1)
printf("Error in reading file.\n");
return -1;
for (i = 0; i < file_s; i++) //look through each byte of filebuff
filebuff[i] = filebuff[i] ^ key[i % keylen];
rewind(files); //move file pointer back to the beginning
//of the file
//write encrypted bytes (in filebuff) back to disk file
if (fwrite(filebuff, file_s, 1, files) != 1)
printf("Error in writing encrypted data to file.\n");
system("pause");
return -1;
free(filebuff); //returning RAM memory back to system
fclose(files);
return 0;
}
此代码中有多个错误。同样在第一部分。你在打电话
fseek(dskfileptr, 0, SEEK_END);
而不为dskfileptr分配任何值。您必须fopen()文件。
“ dskfiles”也是如此。
从不使用变量“字段”。