【问题标题】:Working with files - change just one character处理文件 - 只更改一个字符
【发布时间】:2013-06-16 18:23:40
【问题描述】:

我创建了一个类,允许我使用运算符 [] 获取和更改文件的字符。 问题是,每次我执行程序时,文件由于某种原因变为空。为什么会这样?

#include <iostream>
#include <fstream>
using namespace std;

class FileChar;
class File {
    private:
        ofstream* o_stream;
        ifstream* i_stream;

    public:
        File(char* s);
        ~File();
        void setChar(char c,int position);
        FileChar operator[](int index);
};



// ********************************************* class FileChar *****************************
class FileChar {
    private:
        char c;
        int position;
        File* file;

    public:
        // --- Constructor ---
        FileChar(char c,int position,File* file) :
            c(c),position(position),file(file)
        {}


        // --- cast char ---
        operator char() const {
            return c;
        }


        // --- getChar ---
        char getChar() const {
            return c;
        }


        // --- operator= ---
        FileChar& operator=(char new_c) {
            cout << "operator=" << endl;
            c = new_c;
            file->setChar(c,position);
            return *this;
        }
};


ostream& operator<<(ostream& os,const FileChar& c) {
    cout << "Fdsf";
    os << c.getChar();
    return os;
}





// ************************************************* class File *******************************

    // --- Constructor ---
    File::File(char* s) {
        o_stream = new ofstream(s);
        i_stream = new ifstream(s);
    }


    // --- Destructor ---
    File::~File() {
        o_stream->close();
        i_stream->close();
        delete i_stream;
        delete o_stream;
    }



    // --- setChar ---
    void File::setChar(char c,int position) {
        cout << "setChar" << endl;
        o_stream->seekp(position,ios_base::beg);
        o_stream->put(c);
    }


    // --- operator[] ---
    FileChar File::operator[](int index) {
        cout << "get index " << index << endl;
        i_stream->seekg(index,ios_base::beg);
        char c[2];
        i_stream->get(c,1);
        FileChar f(c[0],index,this);
        return f;
    }







int main() {
    File file("text.txt");
    file[0] = 'H';

    return 0;
}

【问题讨论】:

  • 文件如何打开,什么模式?
  • 什么意思?我在类 File 构造函数中打开了文件。
  • 可以将更多参数传递给ostream构造函数。

标签: c++ file stream


【解决方案1】:

您需要打开文件进行读写。

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多