【说明】
对指定文件中的内容或传入的文本参数进行异或加密/解密,并将加密/解密后的结果保存到文档。可以指定进行异或加密/解密时要使用的私钥。
【命令行示例】
[root@localhost]$ ./magicTransfer xCode 64x
这条命令的含义是如果当前目录下存在 64.txt 这个文本,则对该文本进行解密并将解密结果保存到 64x.txt 文本中;如果不存在 64.txt 文件,则从 a.txt 文件中读取要加密的内容进行加密,并将加密结果保存到 64.txt 文件中。
【源码】
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *pTextOrigin = NULL;
unsigned char magicTransfer(char *_src, const char _ops, FILE *_dest)
{
unsigned char ret = 0;
while(*_src != '\0'){
ret += fprintf(_dest, "%c", ((*_src) ^ _ops));
//printf("%c---%c\n", *_src, ((*_src) ^ _ops));
++_src;
}
return ret;
}
unsigned long readNcount(FILE *_src)
{
char cReadFile;
unsigned long ulCountWord = 0;
while(EOF != fscanf(_src, "%c", &cReadFile)){
//printf("%c", cReadFile);
++ulCountWord;
}
//printf("\nulCountWord is: %d\nsizeof(char) is: %d\n", ulCountWord, sizeof(char));
pTextOrigin = (char *)malloc((size_t)ulCountWord);
//printf("pTextOrigin is: %x\n", pTextOrigin);
return ulCountWord;
}
void work(FILE *_pfSrcFile, char *_pstrDestFileName, char _ops)
{
unsigned long nmemb = 0;
FILE *pf = NULL;
nmemb = readNcount(_pfSrcFile);
//printf("pFile position is: %ld\n", ftell(pFile));
fseek(_pfSrcFile, 0, SEEK_SET);
//printf("pFile position is: %ld\n", ftell(pFile));
//printf("pTextOrigin is: %x\n", pTextOrigin);
printf("Bytes read: %d\n", fread(pTextOrigin, sizeof(char), (size_t)nmemb, _pfSrcFile));
//printf("File context is: %s\n", pTextOrigin);
if (NULL != (pf = fopen(_pstrDestFileName, "wb+"))){ // 进行转换并保存到文件xxx.txt 中
printf("character been transfered: %d\n", magicTransfer(pTextOrigin, _ops, pf));
}
free(pTextOrigin);
fclose(pf);
}
int main(char argc, char **argv)
{
//printf("Num of args: %d\n", argc);
//printf("argv[0] is: %s\n", argv[0]);
char cOperator = 0;
char *cEnd;
FILE *pFile = NULL;
FILE *pFileDest = NULL;
unsigned long nmemb = 0;
char strFilename[10] = "";
if(argc == 3){
if(!strcmp(argv[1], "xCode")){ // 必须以xCode参数开始
if(argv[2]){
cOperator = strtol(argv[2], &cEnd, 10);
//printf("NUM is: %d\ncEnd is: %c\n", cOperator, *cEnd);
sprintf(strFilename, "%d.txt", cOperator);
if(*cEnd == 'x'){ // 操作数必须以x字符结尾
if(NULL == (pFileDest = fopen(strFilename, "rb"))){ // 文件xxx.txt 不存在
printf("Open file %s error! Searching for a.txt ...\n", strFilename);
if(NULL == (pFile = fopen("a.txt", "rb"))){ // 则打开文件a.txt
printf("Open file a.txt error!\n");
}else{
work(pFile, strFilename, cOperator);
fclose(pFile);
}
}else{ // 文件xxx.txt 存在
work(pFileDest, strcat(argv[2], ".txt"), cOperator);
fclose(pFileDest);
}
}else{
printf("Hello, Magic !\n");
}
}else{
printf("Hello, Magic !\n");
}
}else{
printf("Hello, Magic !\n");
}
}else{
printf("Hello, Magic !\n");
}
return 0;
}