http://blog.csdn.net/tianzhijiaozi19/article/details/71773336
http://blog.csdn.net/tianzhijiaozi19/article/details/71773889字符串写入文件 C++ 读文件 将文件内容读入到字符串string中
#include<stdio.h>
#include<iostream>
#include<string>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <stdlib.h>
using namespace std;
string get_bit(char bit);
string encode(string code);
string decode(string code);
char BtoO(string str) ;//二进制转10进制
int flag=0;
//从文件读入到string里
string readFileIntoString(char * filename)
{
ifstream ifile(filename);
//将文件读入到ostringstream对象buf中
ostringstream buf;
char ch;
while(buf&&ifile.get(ch))
buf.put(ch);
//返回与流对象buf关联的字符串
return buf.str();
}
//编码
void Encode()
{
//文件名
char * fn="a.txt";
string str;
str=readFileIntoString(fn);
cout<<str<<endl;
cout<<encode(str)<<endl;
ofstream fout;
// istream fin; 编码后的内容写入文件
fout.open("b.txt");
fout<<encode(str);
fout.close();
}
//解码
void Decode()
{
//文件名
string dec;
char * fn="b.txt";
string str;
str=readFileIntoString(fn);
cout<<str<<endl;
//cout<<encode(str)<<endl;//可以二次编码
reverse(str.begin(),str.end());
dec=decode(str);
cout<<dec<<endl;
ofstream fout;
// istream fin; 编码后的内容写入文件
fout.open("c.txt");
fout<<dec;
fout.close();
}
int main()
{
//源文件a.txt的内容编码后写到b.txt
printf("编码开始:\n");
Encode();
printf("解码开始:\n");
Decode();
//解码
return 0;
}
string get_bit(char bit)
{
string get;
for(int i=0;i<8;i++)
{
get+=(bit&(1<<i)?'.':'-');
}
return get;
}
string encode(string code)
{
string get;
for(int i=0;i<code.length();i++)
{
char bit=code[i];
get.append(get_bit(bit));
}
return get;
}
string decode(string code)
{
string lose="";
string dec="";
int j=0;
for(int i=0;i<code.length();i++)
{
if(code[i]=='.')
//lose[flag++]='1';//
{
lose+='1';
flag++;
}
else
{
lose+='0';
flag++;
//lose[flag++]='0';//error
}
if(flag==8)//一轮8个字符得到一个字节
{
//cout<<lose<<endl;//调试
dec+=BtoO(lose);//
j++;
//dec[j++]=BtoO(lose);//error
lose="";
flag=0;
}
}
//dec[j]='\0';
reverse(dec.begin(),dec.end());
return dec;
}
char BtoO(string str) //二进制转10进制
{
int lg,sum=0,j=1;
char c;
lg=str.length()-1;
for(;lg>=0;lg--)
{
sum=sum+(str[lg]-'0')*j;
j=j*2;
}
//printf("laster: %c\n",sum); //调试
c=sum;
return c;
}
思路:加密原理:用二进制思路。
加密中的for循环是获取二进制内容然后打印,一个字节按位于8次。
解码的只需反向构建即可,加密的逆向。(.表示1)
比如:输入的是ab
则:加密后的是:.----..--.---..- 即为:10000110 01000110 倒转:01100010 01100001 即为——〉b a 然后再次倒转为:a b
如:134 568 各自倒转后431 865 还元整体倒转:568 431 倒转:431 568 独自倒转。
参考:字符串写入文件
示例:#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream fout;
// istream fin;
fout.open("c:\\1.txt");
fout<<"123"<<endl;
fout.close();
return 0;
}
https://zhidao.baidu.com/question/558706893.html