为什么我的 XOR 操作只在我的文本文件的一半上实现
why is my XOR operation only implemented on half of my text file
我正在尝试对文件进行异或。我读入了包含 1 行文本 "this is some random text" 的文件。当我执行 XOR 操作时,我然后输出包含值 00 的 XORed 文件。当我再次对文件进行 XOR 并输出文件中的所有内容时,文件中的所有内容都是 "this is s"。我对所有这些都不熟悉,所以任何信息都会有所帮助。我计划将它用于 .exe 文件,我很好奇这是否对 .txt 文件成功,它是否也适用于 .exe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
//XOR key
#define XOR_KEY 0x6F
void XORFile (char *infile, char *outfile){
FILE *fp;
char buf[4096];
fp = fopen (infile, "r");
fgets (buf, sizeof (buf), fp); //Reading from file
printf ("File contents: %s\n", buf);
int i;
//XOR read file buffer
for(i = 0; buf[i] != '[=10=]'; i++){
buf[i] ^= XOR_KEY;
}
FILE *fp2;
fp2 = fopen (outfile, "w");
fprintf (fp2, "%s", buf);
fclose(fp);
fclose (fp2);
}
int main (int argc, char *argv[]) {
if(argc <= 3){
fprintf (stderr, "Usage: %s [CRYPT] [IN FILE] [OUTFILE]\n", argv[0]);
exit(1);
}
XORFile (argv[2], argv[3]);
return 0;
}
您想使用 fread
而不是 fgets
。您需要将输入和输出视为 binary.
而且,您想循环获取 整个 文件。
事实上,您只会看到第一行。
这好像是 encrypt/decrypt。即使您在 fgets
上循环,它 也不会 用于解密,因为换行符将被异或并且不会给出所需的结果。
这是重构后的版本:
void
XORFile(char *infile, char *outfile)
{
FILE *fp;
FILE *fp2;
int rlen;
char buf[4096];
fp = fopen(infile, "r");
fp2 = fopen(outfile, "w");
while (1) {
rlen = fread(buf,1,sizeof(buf),fp);
if (rlen <= 0)
break;
// XOR read file buffer
for (int i = 0; i < rlen; ++i)
buf[i] ^= XOR_KEY;
fwrite(buf,1,rlen,fp2);
}
fclose(fp);
fclose(fp2);
}
我正在尝试对文件进行异或。我读入了包含 1 行文本 "this is some random text" 的文件。当我执行 XOR 操作时,我然后输出包含值 00 的 XORed 文件。当我再次对文件进行 XOR 并输出文件中的所有内容时,文件中的所有内容都是 "this is s"。我对所有这些都不熟悉,所以任何信息都会有所帮助。我计划将它用于 .exe 文件,我很好奇这是否对 .txt 文件成功,它是否也适用于 .exe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
//XOR key
#define XOR_KEY 0x6F
void XORFile (char *infile, char *outfile){
FILE *fp;
char buf[4096];
fp = fopen (infile, "r");
fgets (buf, sizeof (buf), fp); //Reading from file
printf ("File contents: %s\n", buf);
int i;
//XOR read file buffer
for(i = 0; buf[i] != '[=10=]'; i++){
buf[i] ^= XOR_KEY;
}
FILE *fp2;
fp2 = fopen (outfile, "w");
fprintf (fp2, "%s", buf);
fclose(fp);
fclose (fp2);
}
int main (int argc, char *argv[]) {
if(argc <= 3){
fprintf (stderr, "Usage: %s [CRYPT] [IN FILE] [OUTFILE]\n", argv[0]);
exit(1);
}
XORFile (argv[2], argv[3]);
return 0;
}
您想使用 fread
而不是 fgets
。您需要将输入和输出视为 binary.
而且,您想循环获取 整个 文件。
事实上,您只会看到第一行。
这好像是 encrypt/decrypt。即使您在 fgets
上循环,它 也不会 用于解密,因为换行符将被异或并且不会给出所需的结果。
这是重构后的版本:
void
XORFile(char *infile, char *outfile)
{
FILE *fp;
FILE *fp2;
int rlen;
char buf[4096];
fp = fopen(infile, "r");
fp2 = fopen(outfile, "w");
while (1) {
rlen = fread(buf,1,sizeof(buf),fp);
if (rlen <= 0)
break;
// XOR read file buffer
for (int i = 0; i < rlen; ++i)
buf[i] ^= XOR_KEY;
fwrite(buf,1,rlen,fp2);
}
fclose(fp);
fclose(fp2);
}