#include
#include
#include
#include
using namespace std;
static unsigned int inbfr,outbfr;
static FILE *outfile,*infile;
static int incnt,outcnt,mask;
void init()
{
outbfr=0;
outcnt=8;
inbfr=0;
incnt=8;
mask=0x80; //10000000
}
int getbit()
{
int bitval;
bitval=inbfr&mask; //bitval0000000
incnt--; //7
mask >>= 1; //01000000
bitval >>= incnt;
if (incnt==0)
{
inbfr=fgetc(infile);
incnt=8;
mask=0x80;
}
return bitval; //0000000bitval
}
void putbit( int bitval)
{
outbfr = (outbfr<<1)&255; //00000000
outbfr |= bitval; //0000000bitval
outcnt --;
if (outcnt==0)
{
fputc(outbfr,outfile);
outcnt = 8;
}
}
void alignbits()
{
if (outcnt!=8)
{
for (int i=0;iputbit(0);
}
}
void decode()
{
int n = 3;
int bitsum;
if ((infile = fopen("ciphertext.txt", "rb")) == NULL)
{
printf("cannot open infile!!!\n");
exit(0);
}
if ((outfile = fopen("decryption.txt", "wb")) == NULL)
{
printf("cannot open outfile!!!\n");
exit(0);
}
init();
inbfr = fgetc(infile);
while (!feof(infile))
{
bitsum = 0;
for (int i = 0; i < n; i++) bitsum += getbit();
if (bitsum >= 2) putbit(1);
else putbit(0);
}
alignbits();
fclose(infile);
fclose(outfile);
}
void code()
{
int n = 3;
int bitval;
if((infile=fopen("plaintext.txt","rb"))==NULL)
{
int a;
cout << "请输入数值: ";
cin >> a;
ofstream file_writer("plaintext.txt", ios_base::out);
file_writer << a;
file_writer.close();
}
if ((infile = fopen("plaintext.txt", "w+")) != NULL)
{
int a;
cout << "请输入数值: ";
cin >> a;
ofstream file_writer("plaintext.txt", ios_base::out);
file_writer << a;
file_writer.close();
}
if((outfile=fopen("ciphertext.txt","wb"))==NULL)
{
ofstream infile("ciphertext.txt");
}
init();
inbfr=fgetc(infile);
while(!feof(infile))
{
bitval=getbit();
for (int i=0;iputbit(bitval);
}
alignbits();
ifstream in("ciphertext.txt");
string str;
while (getline(in, str));
cout << "重复码编码后的内容: " << str << endl; //无效读取
in.close();
fclose(infile);
fclose(outfile);
}
int main() {
code();
decode();
}
你先别搞高深的,先从基础开始学起吧
既然涉及到加密解密,你肯定要按二进制读,而不是按字符串读呀
https://blog.csdn.net/TIME_LEAF/article/details/115094365
这种东西随便一搜一大把
读写加个ios::binary,二进制读写
ofstream file_writer("plaintext.txt", ios_base::out | ios::binary);
ifstream file_reader("plaintext.txt", ios_base::in | ios::binary);