读书人

c++中的seekg()函数,该如何解决

发布时间: 2012-08-15 16:57:17 作者: rapoo

c++中的seekg()函数

C/C++ code
        fstream test;    ofstream out;    char str[50], ch;    test.open("C.txt",ios::out);    if(test.fail())        cerr << "1.can't open C.txt!" << endl;    test << "Are you ok?";    test.close();    out.open("tt.txt", ios::out);    if(out.fail())        cerr << "can't open tt.txt!" << endl;    test.open("C.txt",ios::in);    cout << "1.test.is_open():" << test.is_open() << endl;    if(test.fail())        cerr << "2.can't open C.txt!" << endl;    while(test.get(ch))    {        cout << "ch=" << ch << endl;        out.put(ch);    }    out.close();    //cout << "2.test.is_open():" << test.is_open() << endl;    test.seekg(0);//将指针重置回文件0起始位置    cout << test.tellg() << endl;    test.get(str, 13);    cout << "str[50]=" << str << endl;    fstream test;    ofstream out;    char str[50], ch;    test.open("C.txt",ios::out);    if(test.fail())        cerr << "1.can't open C.txt!" << endl;    test << "Are you ok?";    test.close();    out.open("tt.txt", ios::out);    if(out.fail())        cerr << "can't open tt.txt!" << endl;    test.open("C.txt",ios::in);    cout << "1.test.is_open():" << test.is_open() << endl;    if(test.fail())        cerr << "2.can't open C.txt!" << endl;    test.get(str, 13);    test.seekg(0);//将指针重置回文件0起始位置    while(test.get(ch))    {        cout << "ch=" << ch << endl;        out.put(ch);    }    out.close();    //cout << "2.test.is_open():" << test.is_open() << endl;    cout << test.tellg() << endl;    cout << "str[50]=" << str << endl;



请问为什么前面一种方法(注释那里)str[50]为空的,后面一种却可以

[解决办法]
C/C++ code
// get length of file:  test.seekg (0, ios::end);  length = test.tellg();  test.seekg (0, ios::beg);
[解决办法]
C/C++ code
    fstream test;    ofstream out;    char str[50], ch;    test.open("C.txt",ios::out);    if(test.fail())        cerr << "1.can't open C.txt!" << endl;    test << "Are you ok?";    test.close();    out.open("tt.txt", ios::out);    if(out.fail())        cerr << "can't open tt.txt!" << endl;    test.open("C.txt",ios::in);    cout << "1.test.is_open():" << test.is_open() << endl;    if(test.fail())        cerr << "2.can't open C.txt!" << endl;    while(test.get(ch))    {        cout << "ch=" << ch << endl;        out.put(ch);    }//这个while已经让test到了流中字符串的结尾处    out.close();    //cout << "2.test.is_open():" << test.is_open() << endl;    test.seekg(0);//将指针重置回文件0起始位置    cout << test.tellg() << endl;//输出为11,也就是流的结尾    test.get(str, 13);//从流的结尾开始给str赋值,输出肯定为空的    cout << "str[50]=" << str << endl;
[解决办法]
用test.seekg (0, ios::end);
试试看。
[解决办法]
...学习...

读书人网 >C++

热点推荐