c++ - 从文件中读取数据

标签 c++ visual-c++ mfc

我正在开发一个需要在文件中存储数据的 MFC 应用程序

我有这样一个类

class Client
{
public:
    Client(CString Name , CString LastName , CString Id );
    int create();
    int update(Client & myClient);

    CString name;
    CString lastName;
    CString id;
};



Client::Client(CString Name , CString LastName , CString Id )
{
    name = Name;
    lastName=LastName;
    id=Id;
}

void displayMessage(CString message , CString title=L"Meesage")
{
    MessageBox(NULL,message,title,MB_OK | MB_ICONERROR);
}


    int Client::create(Client myClient)
    {
        ofstream output;
        output.open("test.dat" , ios::binary );
        if( output.fail() )
        {
            CString mess;
            mess = strerror( errno );
            displayMessage(mess);
            return 1 ;//anything but 0
        }


        output.write( (char *) &myClient , sizeof(Client));
        output.close();

        return 0;
    }


    int Client::update(Client & myClient)
    //also tried passing by value : int update(Client myClient)
    {
        ifstream input;
        input.open("test.dat" , ios::binary );
        if( input.fail() )
        {
            CString mess;
            mess = strerror( errno );
            displayMessage(mess);
            return 1 ;//anything but 0
        }


        input.read( (char *) &myClient , sizeof(Client));
        input.close();

        return 0;
    }

创建功能运行良好,

但是,关于更新功能我有一些问题

我使用这样的函数:

Client myClient();
myClient.update(myClient);

但是当我运行这个函数时出现了这个错误

 Unhandled exception at 0x5adfab2a (mfc100ud.dll) in MyProject.exe: 0xC0000005: Access violation writing location 0x039708fc.

我能做什么?

最佳答案

小心。 客户端 myClient(); declares a function名为 myClient。写入函数的地址会导致一些问题,比如崩溃。只需将其更改为 Client myClient;(这样您就可以创建一个实际的 Client 对象,然后实际写入一个对象)。当然,我希望像那样写入 Client 对象是安全的(例如,请参阅 Joachim Pileborg 关于指针的评论)。

例如,看下面的代码:

#include <typeinfo>
#include <iostream>

struct S {};

int main()
{
    S s1();
    S s2;
    std::cout << typeid(s1).name() << std::endl;
    std::cout << typeid(s2).name() << std::endl;
}

The results (使用 g++)打印出来:

F1SvE
1S

重要的一点是它们不一样! s1 是名为 s1 的函数的声明,该函数不带参数并返回 Ss2 是一个实际的 S 对象。这被称为 C++ 的“最令人烦恼的解析”(因为它会导致很多挫败感)。

编辑:天啊,你不断用更多(实际)代码更新你的问题,这会不断改变事情。为了将来引用,只需从完整的实际代码开始,这样人们就不必不断更改内容:)

您不能像那样安全地编写 CString。它们在内部存储指针,就像 Joachim Pileborg 提到的那样,在尝试读入它们时会造成严重破坏。

此外,Client 不再有默认构造函数(因为您已经提供了自己的构造函数)。所以你也不能再说 Client myClient; 了。您必须使用正确的构造函数。

关于c++ - 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14415644/

相关文章:

c++ - 来自 MFC 的调用 Access 2007 报告

c++ - 当在命令行上指定要打开的文件时,MFC 应用程序在 ProcessShellCommand() 中崩溃

c++ - std::list 的 const_iterator 与迭代器

c++ - 如何使用 boost::joined_range 实现范围适配器

c++ - 在Visual Studio C++中写入函数引发读取访问冲突异常

c++ - 错误 C2664 : in c++?

.net - 将托管 C++ 添加到 C# GUI

c++ - 输入迭代器的相等比较

c++ - Visual C++ 构建/调试问题

c++ - 功能区组合框间距和对齐方式