我正在开发一个需要在文件中存储数据的 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
的函数的声明,该函数不带参数并返回 S
。 s2
是一个实际的 S
对象。这被称为 C++ 的“最令人烦恼的解析”(因为它会导致很多挫败感)。
编辑:天啊,你不断用更多(实际)代码更新你的问题,这会不断改变事情。为了将来引用,只需从完整的实际代码开始,这样人们就不必不断更改内容:)
您不能像那样安全地编写 CString
。它们在内部存储指针,就像 Joachim Pileborg 提到的那样,在尝试读入它们时会造成严重破坏。
此外,Client
不再有默认构造函数(因为您已经提供了自己的构造函数)。所以你也不能再说 Client myClient;
了。您必须使用正确的构造函数。
关于c++ - 从文件中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14415644/