0
我不確定我在做什麼錯,試圖編寫一個簡單的程序,在重命名後運行後加密。當該方法運行兩次時,它應該做同樣的事情,但它解密文件。第一個版本可以工作,但是它留下了舊版本,並且創建了一個新版本,並且我想要一個程序,我可以運行一次來加密並再次解密,以允許我在過程中更改文件擴展名,以方便起見。C - 寫入二進制失敗(重寫文件)
當我運行該程序時,它在fwrite()上崩潰。
#include <stdio.h>
#include <stdlib.h>
#define KEY '&'
int main(void)
{
FILE *fp; // file pointer
size_t size, test; // file size
char src_file[FILENAME_MAX], dst_file[FILENAME_MAX];
int orig_char, new_char;
int i = 0;
printf("Enter the name of the source file \"file.ext\": ");
scanf("%s", src_file);
if ((fp = fopen(src_file, "rb")) == NULL) { // open file
fprintf(stderr, "Can't open \"%s\"\n", src_file);
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END); // find the end of file
size = ftell(fp); // file size
fseek(fp, 0, SEEK_SET); // set file position to start
unsigned char buffer[size], *temp = buffer; //buffer
test = fread(buffer, sizeof(buffer[0]), size, fp);
printf("size written: %d, size of file: %d\n", test, size);
if (test != size) {
fprintf(stderr, "Error: operation fwrite failed!\n");
exit(EXIT_FAILURE);
}
fclose(fp);
printf("Enter the name of the destination file \"file.ext\": ");
scanf("%s", dst_file);
if ((fp = fopen(src_file, "wb")) == NULL) {
fprintf(stderr, "Can't open \"%s\"\n", dst_file);
exit(EXIT_FAILURE);
}
puts("Test1");
for (i = 0; (size_t)i < size && orig_char != EOF; i++, temp++) {
orig_char = (int) *temp;
new_char = orig_char^KEY;
*temp = new_char;
}
puts("Test3");
test = fwrite(buffer, sizeof(buffer[0]), size, fp);
fclose(fp);
free(buffer);
if ((rename(src_file, dst_file)) != 0)
fprintf(stderr, "Failed to rename file, make sure file doesn't" \
"already exist!\n");
return 0;
}
對不起,我想通了,我忘了刪除免費(緩衝區);一旦我將其改爲指針 –
我仍然很感激任何關於更改我的代碼的輸入以清除它並使其看起來更好。 –
你應該做的是在http://codereview.stackexchange.com/上發佈工作代碼。堆棧溢出重點解決特定的技術問題。 – Lundin