#define _CRT_SECURE_NO_WARNINGS
#define SRC_PATH "C:\\Users\\michael\\Desktop\\yzh.txt"
#define CODE_PATH "C:\\Users\\michael\\Desktop\\yzh_code.txt"
#define DECODE_PATH "C:\\Users\\michael\\Desktop\\yzh_decode.txt"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getFileSize_C(char * file)
{
int size = -1;
FILE * path;
path = fopen(file, "r");
if (NULL == path)
{
printf("文件打开失败!\n");
return size;
}
else
{
fseek(path, 0, SEEK_END);
size = ftell(path);
fclose(path);
path = NULL;
}
return size;
}
void code_decode_file_with_psw(char* path, char* newpath,char* psw)
{
FILE* pRead = fopen(path, "r");
FILE* pWrite = fopen(newpath, "w");
if (pRead == NULL || pWrite == NULL)
{
return;
}
else
{
int ch = 0;
int fileSize = getFileSize_C(path);
int pswLength = strlen(psw);
for (int i = 0; i < fileSize / pswLength; i++)
{
for (int j = 0; j < pswLength; j++)
{
ch = fgetc(pRead);
fputc(ch^psw[j], pWrite);
}
}
for (int k = 0; k <fileSize % pswLength; k++)
{
ch = fgetc(pRead);
fputc(ch^psw[k], pWrite);
}
}
fclose(pRead);
fclose(pWrite);
pRead = NULL;
pWrite = NULL;
}
void main()
{
code_decode_file_with_psw(SRC_PATH, CODE_PATH,"yzh");
code_decode_file_with_psw(CODE_PATH, DECODE_PATH,"yzh");
system("pause");
}
说明:文本文件使用密码加密时,不能使用r,w方式打开文件。应该使用rb,wb。