c++ - 我可以在main之前创建fstream吗?

标签 c++ fstream

#include <string.h>
#include <fstream>

using namespace std;
ofstream fout(argv[1]);
主功能
int main(int argc, const char * argv[]) {
//I try to add "new word" fstream file
fout<<"new words"<<endl;
}
我怎样才能做到这一点?最底层的也不起作用。这是必需品。必须在主要功能之前
#include <string.h>
#include <fstream>

using namespace std;

string argument;
ofstream fout(argument]);
主功能
int main(int argc, const char * argv[]) {
argument=argv[1]
fout<<"new words"<<endl;
}

最佳答案

在知道fout是什么之前,您无法初始化argv。因此,从某种意义上讲,是不可能的。但是,您可以不进行任何初始化,然后在获得open时对其进行argv:

ofstream fout;

int main(int argc, const char * argv[])
{
    fout.open(argv[1]);
    fout<<"new words"<<endl;
}
这样,全局fout对其之后定义的所有函数都可以访问。但是,在main无效的情况下,有很短的时间在fout中打开它。从逻辑的 Angular 来看,这是您可以做的最好的事情。

关于c++ - 我可以在main之前创建fstream吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64885304/

相关文章:

c++ - ifstream 读取二进制数据发出 0x00 字节

c++ - fstream 未在 C++ 中创建文件

C++ fstream 混淆

c++ - 在qml中恢复最小化的无框窗口

c++ - 如果 TECGetTextEncodingFromInternetName() 需要 Pascal 风格的字符串,为什么 CopyCStringToPascal() 在 OSX 10.5 中停用了?

c++ - fork 一次然后在不同的过程中使用线程?

c++ - 在Mac上找不到ifstream'文件

c++ - 将 char 变量传递给类型字符串函数

c++ - 当char数组被过度填充时,为什么我的程序会陷入无限循环?

c++ - 了解以下情况……fstream 何时打开文件以及何时不打开文件