gpt4 book ai didi

c++ - 类中的 Fstream 初始化 - 检查文件是否打开

转载 作者:太空宇宙 更新时间:2023-11-04 14:10:26 25 4
gpt4 key购买 nike

例子:

//头文件

class Example
{
private:
fstream InputObject;

public:
Example();

}

//执行文件

Example::Example():InputObject("file_name.txt", ios::in) {}

从我目前从类似问题中读到的内容来看,在“旧”版本的 C++ 中,初始化类中的 fstream 对象的唯一方法是通过上面所示的成员列表初始化来完成。

问题:
如果这真的是在类中初始化 fstream 对象的“唯一”方式,那么如果文件无法打开我们该怎么办?

通常我会通过检查运行 fstream 对象以确保它正确打开,但在这种情况下这似乎不可能。此外,即使我可以,如果第一次未能重新初始化对象,我又该如何重新初始化?

最佳答案

#define WIN32_LEAN_AND_MEAN // This makes it so it doesn't look through libs that are not included when running

#include <fstream> //To Read write to files, to be able to
#include <iostream> // The basic stuff, cout, cin, etc.
using namespace std; // the capability of typing cout instead of std::cout
int main() // our main loop
{
fstream InputObject; // declaring InputObject as something that can write to a file
if(!Inputobject.open("File Name Here") // if it cant open the file
{
cout << "File not Open" << endl; // then write to console, " File not Open"
}

return 0;
system("pause");
}

你想知道文件是否打开,所以使用 !在用于打开文件的函数意味着未打开之前,所以带有 !InputObject.open 的 if 语句将检查它是否未打开,如果是,则执行某些操作,因此 cout << "File is not open"会告诉你是否打开。

关于c++ - 类中的 Fstream 初始化 - 检查文件是否打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com