首页 新闻 会员 周边

为什么文件里会出现一些奇怪的字符?代码如下

-1
悬赏园豆:5 [已解决问题] 解决于 2016-07-28 12:43
#include<iostream>//设计一个测试seekg()的程序
#include<fstream>
#include<string>
class Chih
{
    std::ifstream in;
    std::ofstream out;
    int a;
    std::string file;
    std::string file1;
public:
    Chih();
    ~Chih();
    void Check();
};
Chih::Chih()
{
    std::cout << "Write your file name: ";
    std::cin >> file;
    in.open(file, std::ios::binary);
    if (!in)
    {
        std::cout << "failed to open your file -o-!" << std::endl;
        exit(1);
    }
    std::cout << "Input your storage file name: ";
    std::cin >> file1;
    out.open(file1, std::ios::binary);
    if (!out)
    {
        std::cout << "failed to open storage file 0-0!";
        exit(1);
    }
}
Chih::~Chih()
{
    in.close();
    out.close();
}
void Chih::Check()
{
    char buf[1000];
    in.seekg(2, std::ios::beg);//seekg难道也是ifstream的成员函数吗?
    in.read((char*)&buf, sizeof(buf)/5);
    //out.seekg(20,std::ios::cur);//seekg()是类istream和ostream的成员函数
    out.write((char*)&buf, sizeof(buf)/5);
}
int main()
{
    Chih du;
    du.Check();
    return 0;
}

第二个注释是编这个程序的时候遇到的另一个问题。

爱是用心码不要说话的主页 爱是用心码不要说话 | 初学一级 | 园豆:154
提问于:2016-05-17 08:54
< >
分享
最佳答案
1

你指的是从一个文件中读取出数据然后写入另一个文件中,在新写入的文件中出现了乱码吧!

我测试了你的程序,在写入英文时是不会出现乱码的,只有在写入中文时才会有

原因如下:

   1,in.seekg(2, std::ios::beg);这行代码表示将文件读取指针从文件头开始向后移动两个字节,如果是中文,你移动两个字节再读取,那么中文的编码就不完整,所以读取出来就会是乱码,写入的当然也就是乱码了。

   2,如果你读取的文件本身有乱码,那么写入的也一样

   //经过我的测试,原因就是第1个

第二个注释是因为std::ofstream对象没有seekg这个成员函数,在ostream中也没有seekg函数定义,但istream有,而std::ofstream是从ostream派生的。

收获园豆:5
WKOOKW | 菜鸟二级 |园豆:207 | 2016-06-07 16:09
其他回答(1)
0
void Chih::Check()
{
    char buf[1000];
    in.seekg(2, std::ios::beg);//seekg难道也是ifstream的成员函数吗?


//第一个参数用的有问题, buf已经是一个char *类型了,再取地址,运气好是可以正常工作的,运行差,程序会崩溃
in.read((char*)&buf, sizeof(buf)/5); //out.seekg(20,std::ios::cur);//seekg()是类istream和ostream的成员函数

//这里也一样
out.write((char*)&buf, sizeof(buf)/5); }

 

manziluo | 园豆:202 (菜鸟二级) | 2016-08-19 17:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册