读书人

问下:如何写dat文件

发布时间: 2012-04-25 19:32:32 作者: rapoo

问下:怎么写dat文件?
我需要将用户名和密码写入到dat文件,能说下怎么写吗 有代码给更好

[解决办法]

C/C++ code
using namespace std;struct stUser{    char sName[20];    char sPwd[20];};//简单加密int Encode(char *pBuff,int nLen){    for (int i=0;i<nLen;i++)    {        *pBuff+=4;        pBuff++;    }    return nLen;}//简单解密int DeCode(char *pBuff,int nLen){    for (int i=0;i<nLen;i++)    {        *pBuff-=4;        pBuff++;    }    return nLen;}void main(){    FILE *fp = fopen("c:\\1.dat","wb");    if (fp==NULL)        return;    stUser st = {"henry","123456"};    char* pBuff = (char*)&st;    int nLen = Encode(pBuff,sizeof(st));    fwrite(pBuff,sizeof(char),nLen,fp);//加密后写文件    fclose(fp);    //读取    fp = fopen("c:\\1.dat","rb");    if (fp==NULL)        return;    stUser st2={0};    pBuff = (char*)&st2;    nLen = sizeof(st2);    fread(pBuff,sizeof(char),nLen,fp);//读文件后解密    DeCode(pBuff,nLen);    fclose(fp);    printf("sUser:%s\tsPwd:%s\n",st2.sName,st2.sPwd);    system("pause");    }
[解决办法]
写个C++风格版的
C/C++ code
#include <string> #include <algorithm>#include <fstream>using namespace std;class Record{public:    char acc[20];    char pwd[20];};// 加密解密都用它const char encrypte(const char c){    static const string k("You can change this.");    static size_t i = 0;    return c^k[i=(i+1)%k.length()];}int main(){    // 把rec1加密写到文件    Record rec1 = {"abcdef", "aA1_&"};    ofstream ofs("record.dat", ios::binary);    transform((char *)&rec1, (char *)&rec1+sizeof(Record),        ostreambuf_iterator<char>(ofs.rdbuf()), encrypte);    ofs.close();    // 从文件解密到rec2    Record rec2;    ifstream ifs("record.dat", ios::binary);    transform(istreambuf_iterator<char>(ifs.rdbuf()), istreambuf_iterator<char>(),        (char *)&rec2, encrypte);    return 0;} 

读书人网 >C++

热点推荐