【发布时间】:2018-05-06 21:49:54
【问题描述】:
我正在编写一个程序,从文本文件中一次读取 4 个字符,将它们打包成一个整数,通过将整数向右移动 3 个单位来“加密”整数,然后将加密后的整数写入一个二进制文件。
原码:
#include <stdio.h>
#include <limits.h>
#include "encoding.h"
#define KEY 3
int encrypt(int a);
int pack(char a, char b, char d, char c);
void encoding(char itxt[], char obin[]){
char four[4];
FILE *inp=fopen(itxt,"r");
if(!inp){printf("Unable to open %c", inp); return 1;}
FILE *outp=fopen(obin,"wb");
if(!outp){printf("Unable to open %c\n", obin); return 1;}
while(fgets(four, 4, inp) != NULL){
int a;
a = pack(four[0], four[1], four[2], four[3]);
a = encrypt(a);
fwrite(&a, sizeof(int), 1, outp);
}
printf("Encoding complete!\n");
fclose(inp);
fclose(outp);
}
int pack(char a, char b, char c, char d){
int p = a;
p = (p<<CHAR_BIT) | b;
p = (p<<CHAR_BIT) | c;
p = (p<<CHAR_BIT) | d;
return p;
}
int encrypt(int a){
int obin = a>>KEY;
return obin;
}
代码编译但不向二进制文件写入任何内容。任何反馈、提示或提示将不胜感激。
提前致谢!
*编辑:
#include <stdio.h>
#include <limits.h>
#include "encoding.h"
#define KEY 3
unsigned int encrypt(int a);
unsigned int pack(char a, char b, char d, char c);
void encoding(char itxt[], char obin[]){
char four[4];
FILE *inp=fopen(itxt,"r");
if(!inp){printf("Unable to open %c", inp); return 1;}
FILE *outp=fopen(obin,"wb");
if(!outp){printf("Unable to open %c\n", obin); return 1;}
while(fread(&four, sizeof(char), 4, inp) != NULL){
unsigned int a;
a = pack(four[0], four[1], four[2], four[3]);
a = encrypt(a);
fwrite(&a, sizeof(unsigned int), 1, outp);
}
printf("Encoding complete!\n");
fclose(inp);
fclose(outp);
}
unsigned int pack(char a, char b, char c, char d){
int p = a;
p = (p<<CHAR_BIT) | b;
p = (p<<CHAR_BIT) | c;
p = (p<<CHAR_BIT) | d;
return p;
}
unsigned int encrypt(int a){
int obin = (a>>KEY) | (a<<(CHAR_BIT*sizeof(a)-KEY));
return obin;
}
【问题讨论】:
-
是否调用了 encoding()?我们没有看到这部分代码
-
encoding() 在单独的文件 main.c 中调用。我没有包含它,它只是显示原始文本文件,调用 encoding()、decoding(),并显示生成的文本文件。
-
对于初学者,
pack的返回类型是char。这永远不会给你你正在寻找的结果。此外,>>运算符不是循环的。高位将用零填充...好吧,可能...这确实是未定义的行为,因为您正在移动带符号的数据类型。 -
如果确实调用了
encoding,并且您没有看到任何错误(并且输入文件包含某些内容),即使加密/打包错误,您也应该在写入的文件中看到结果。 -
您还应该使用
fread(),因为fgets(four, 4, inp)可能会返回1 到3 个字符加上一个空字节。如果碰巧有换行符,它将返回少于 3 个字符。它永远不会返回 4 个非空字符。
标签: c unix binary bitwise-operators