如何使用fstream指针对文件进行操作?

ran*_*nk1 1 c++ fstream

我想使用一些抽象操作流,因此我想使用fstream*而不是ifstream和ofstream.我试着做那样但是会导致访问违规:

char* text= "test"; 
fstream* o = new fstream(); 
o = &fstream("name.txt"); 
o->write(text, 4); 
o->close();
Run Code Online (Sandbox Code Playgroud)

我该如何解决它,或者使用其他想法?

我想在这种情况下使用指针(您可以在这里查看更多一般信息)如何在C++中实现我自己的IO文件API

更改后,它现在看起来像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

主要:

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();
Run Code Online (Sandbox Code Playgroud)

这段代码似乎工作,我找不到文件.我检查了当前目录是否正确指向(ProjectName/Debug)

我检查了它并将fstream更改为ofstream将按预期工作,我可以找到该文件.但是因为我想实现某种程度的抽象,我想使用fstream.我该如何解决?

Jos*_*eld 8

此代码将给您一个错误,因为您不能像正在使用的那样获取临时对象的地址&fstream("name.txt").

error: taking address of temporary
Run Code Online (Sandbox Code Playgroud)

另请注意,从字符串文字到a的转换char*已被弃用,在C++ 11中无效.用一个const char*代替:

const char* text = "test";
Run Code Online (Sandbox Code Playgroud)

尽管如此,让我们来看看你想要做什么.首先,您正在动态分配fstream并初始化指向该对象的指针:

fstream* o = new fstream();
Run Code Online (Sandbox Code Playgroud)

然后在下一行中,创建一个临时对象,fstream("name.txt")然后获取其地址并将其分配给o(如我们所见,这会产生错误).现在您将丢失对动态分配的任何访问权限fstream,而是o指向现在已销毁的临时对象.

取消引用该指针(带o->)将为您提供未定义的行为.

你这太复杂了.您根本不需要动态分配fstream对象或使用指针.相反,尝试:

fstream o("name.txt");
o.write(text, 4);
o.close();
Run Code Online (Sandbox Code Playgroud)

使用更新的代码,问题是您正在写0字节:

plik->write(napis, 0);
Run Code Online (Sandbox Code Playgroud)

也许你的意思是:

plik->write(napis, 6);
Run Code Online (Sandbox Code Playgroud)