简体   繁体   English

用C ++进行文件读写

[英]Writing/ Reading from File in C++

I have created a simple program which writes an object to a file and then reads back whats written to the file. 我创建了一个简单的程序,该程序将对象写入文件,然后读回写入文件的内容。 My problem is when i write to the file unwanted values get written to the file and when i retrieve back the data , those values also get retrieved , which i don't want. 我的问题是,当我将文件写入文件时,不需要的值将被写入文件,而当我取回数据时,这些值也将被检索到,这是我不想要的。

Here is what i have done : 这是我所做的:

File Handling Implementation 文件处理实施

//File Handling class Implementation
File::File(){}

string File::writeObject(Person obj)
{
    ofstream outFile("myFile.txt", ios::out);

    if( !outFile ) {
        cout << "No File" << endl;
    }

    outFile.write( reinterpret_cast<const char *> (&obj), sizeof(obj) );
    return "Done";
}

Person.H: 人.H:

//Person.H
class Person {
    private: string name;
    public: Person();
    public: void setName(string name);
    public: string getName();   
};

Main Implementation : using namespace std; 主要实现:使用命名空间std;

int main( int argc, char* argv[] )
{
    Person p1;
    p1.setName("Shehan");

    File f1;

    cout << f1.writeObject(p1) << endl; //writes to the file

    ifstream readFile("myfile.txt",ios::in); creates object to read from file

    string name; // creates variable to hold the value
    readFile >> name; reads from file

    cout << name << endl; //prints the value
    system("pause");

    return 0;
}

I think only "shehan" should be written to the file but what's written to the file is: 我认为应该仅将“ shehan”写入文件,但写入文件的内容是:

0ÂÒ Shehan ÌÌÌÌÌ'þ¨

When i read again : 当我再次阅读时:

在此处输入图片说明

What seems to be the problem here? 这里似乎是什么问题?

What is going on here is that you aren't formatting the output. 这里发生的是您没有格式化输出。 All output must be formatted in some way, in order to ensure that you can reread it; 必须以某种方式格式化所有输出,以确保您可以重新读取它。 just copying the bit pattern from memory is useless. 仅从内存中复制位模式是没有用的。

The usual way of handling this would be to define an operator << (and an operator >> , in order to read) for your class. 通常的处理方式是为您的类定义一个运算符<< (和一个>>以便读取)。 This operator will output all of the individual elements of the class, with appropriate separators so that you can determine where one ends and the next begins when you read. 该运算符将输出该类的所有单个元素,并带有适当的分隔符,以便您在阅读时可以确定哪一个结束,下一个开始。 If, for example, we take a simple example: 例如,如果我们举一个简单的例子:

class Person
{
    std::string name;
    int age;
public:
    //  ...
    friend std::ostream& operator<<( std::ostream& dest, Person const& obj )
    {
        dest << '"' << name << '"' << age;
        return dest;
    }

    friend std::istream& operator>>( std::istream& source, Person& obj )
    {
        char ch;
        source >> ch;
        if ( ch != '"' ) {
            source.setstate( std::ios_base::failbit );
        }
        std::string name;
        while ( source.get( ch ) && ch != '"' ) {
            name += ch;
        }
        if ( ch != '"' ) {
            source.setstate( std::ios_base::failbit );
        }
        int age;
        source >> age;
        if ( source ) {
            obj = Person( name, age );
        }
        return source;
    }
};

You'll notice that input is a lot more difficult than output. 您会注意到输入比输出困难得多。 When outputting, you know what you've got (because of the C++ type system, and your own verification of class invariants). 输出时,您知道所拥有的(由于C ++类型系统,以及您自己对类不变式的验证)。 When inputting, you never know what the user is going to give you, so you have to check for all possibilities. 在输入时,您永远都不知道用户会给您什么,因此您必须检查所有可能性。 (You might, for example, want to forbid additional characters like a '\\n' in the name. Just add them to the test in the while .) (例如,您可能想禁止名称中的其他字符,例如'\\n' 。只需在while中将它们添加到测试中即可。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM