FridayNightInSummer 2017-06-03 03:02 采纳率: 0%
浏览 804

提问 c++文件操作的问题

#include
#include
using namespace std;

char ch,;

void test(fstream &file) //检测是否打开
{
if (file.fail())
{
cout << "不能打开文件" << endl;
exit(0);
}
cout << "文件打开成功,并读取数据" << endl;
}

int main()
{
fstream ori_file; //原文件
fstream ser_file; //加密后的文件

ori_file.open("E:\\20163653\\myfile1.txt", ios::in);
ser_file.open("E:\\20163653\\myfile2.txt", ios::out | ios::in);
test(ori_file);
test(ser_file);

cout << "原来的文件内容为:" << endl;
while (!ori_file.eof())   //从原文件中读取字符并加密后放到加密文件中
{
    ori_file.get(ch);
    if (ori_file.fail())
        break;
    cout << ch;
    ch = ch ^ 0x6a;
    ser_file.put(ch);
}
//ori_file.close();
//ser_file.close();

//ser_file.open("E:\\20163653\\myfile2.txt", ios::in);
cout << endl << "加密后的文件内容为:" << endl;
while (!ser_file.eof())
{
    ser_file.get(ch);
    if (ser_file.fail())
        break;
    cout << ch;
}
//ser_file.close();

//ser_file.open("E:\\20163653\\myfile2.txt", ios::in);
//cout << endl;

cout << endl << "解密后的文件内容为:" << endl;
while (!ser_file.eof())
{
    ser_file.get(ch);
    if (ser_file.fail())
        break;
    ch = ch ^ 0x6a;
    cout << ch;

}
cout << endl;
ser_file.close();


return 0;

}

一个加密文件的程序,运行结果是第二部输出加密文件时是屯屯屯屯,假如把先把文件关掉再打开就可以运行了,这是怎么回事
请各位大佬赐教

  • 写回答

1条回答 默认 最新

  • huangzongw 2017-06-05 17:51
    关注

    cout << endl << "加密后的文件内容为:" << endl;

    // 刚写完文件,文件流位置位于末尾,应该增加此行,把位置流位置移到文件头,再读取
    ser_file.seekp(ios::beg);

    while (!ser_file.eof())
    {
    ser_file.get(ch);
    if (ser_file.fail())
    break;
    cout << ch;
    }

    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能