我想使用一些抽象对流进行操作,因此我想使用fstream*而不是ifstream和ofstream。我试着做这样的事,但会导致访问违规:
char* text= "test";
fstream* o = new fstream();
o = &fstream("name.txt");
o->write(text, 4);
o->close();我怎样才能修复它,或者使用另一个想法呢?
我想在本例中使用指针(您可以在这里查找更多的一般信息) How to implement my own IO file API in C++
经过这些更改之后,现在看起来如下所示:
class GIO_Persistent_File_System : public GIO_CORE
{
public:
GIO_Persistent_File_System(void);
int open(char*, int);
int close();
void write(char* s, int size);
void read(char* s, int size);
public:
~GIO_Persistent_File_System(void);
private:
fstream file;
};
int GIO_Persistent_File_System::open(char* path, int mode){
file.open(path);
return 0;
}
int GIO_Persistent_File_System::close(){
file.close();
return 0;
}
void GIO_Persistent_File_System::write(char* s, int size){
file.write(s, size);
return;
}
void GIO_Persistent_File_System::read(char* s, int size){
file.read(s, size);
return;
}主要:
GIO_CORE* plik = new GIO_Persistent_File_System();
char* test = new char[10];
char* napis = "testgs";
plik->open("name.txt", OPEN_MODE);
plik->write(napis, 2);
//plik->read(test,2);
plik->close();这段代码看起来就像在工作一样,我找不到文件。我检查并正确指向当前目录(ProjectName/Debug)
我检查了它,而将fstream改为ofstream将按其应有的工作,我可以找到该文件。但是,由于我想实现某种程度的抽象和,所以我想使用fstream。我怎么才能修好它?
发布于 2013-03-28 14:11:59
这段代码会给出一个错误,因为您不能像使用&fstream("name.txt")那样获取临时对象的地址。
error: taking address of temporary另外,请注意,从字符串文本到char*的转换已被废弃,在C++11中是无效的。
const char* text = "test";尽管如此,让我们看看你想做什么。首先,动态分配一个fstream并初始化指向该对象的指针:
fstream* o = new fstream();然后在下一行中,使用fstream("name.txt")创建一个临时对象,然后获取它的地址并将其分配给o (正如我们所看到的,这会产生一个错误)。现在,您将失去对动态分配的fstream的任何访问,而是让o指向一个现已销毁的临时对象。
删除该指针(使用o->)将给您提供未定义的行为。
你把事情搞得太复杂了。您根本不需要动态分配fstream对象或使用指针。相反,试着:
fstream o("name.txt");
o.write(text, 4);
o.close();使用更新的代码,问题是您正在编写0字节:
plik->write(napis, 0);也许你的意思是:
plik->write(napis, 6);发布于 2013-03-28 14:13:41
几乎不需要有指向fstream的指针。就这么做吧:
std::ofstream o("name.txt");
o.write(napis, 4);
o.close();注意,当o超出作用域时,它也会关闭,因此您甚至不需要调用close()。
https://stackoverflow.com/questions/15684052
复制相似问题