简体   繁体   English

用字符串名称打开输出文件流

[英]opening output filestreams with string names

Hi I have some C++ code that uses user defined input to generate file-names for some output files: 嗨,我有一些C ++代码,使用用户定义的输入为一些输出文件生成文件名:

std::string outputName = fileName;
for(int i = 0; i < 4; i++)
{
    outputName.pop_back();
}
std::string outputName1 = outputName;
std::string outputName2 = outputName;
outputName.append(".fasta");
outputName1.append("_Ploid1.fasta");
outputName2.append("_Ploid2.fasta");

Where fileName could be any word the user can define with .csv after it eg '~/Desktop/mytest.csv' 其中fileName可以是用户可以使用.csv定义的任何单词,例如'〜/ Desktop / mytest.csv'

The code chomps .csv off and makes three filenames / paths for 3 output streams. 该代码将.csv关闭并为3个输出流创建三个文件名/路径。

It then creates them and attempts to open them: 然后它创建它们并尝试打开它们:

std::ofstream outputFile;
outputFile.open(outputName.c_str());
std::ofstream outputFile1;
outputFile1.open(outputName1.c_str());
std::ofstream outputFile2;
outputFile2.open(outputName2.c_str());

I made sure to pass the names to open as const char* with the c_str method, however if I test my code by adding the following line: 我确保使用c_str方法将名称传递给const char *,但是如果我通过添加以下行来测试我的代码:

std::cout << outputFile.is_open() << " " << outputFile1.is_open() << " " << outputFile2.is_open() << std::endl;

and compiling and setting fineName as "test.csv". 并将fineName编译并设置为“test.csv”。 I successfully compile and run, however, 我成功编译并运行,但是,

Three zeros's are printed to screen showing the three filestreams for output are not in fact open. 屏幕上会打印三个零,表示输出的三个文件流实际上并未打开。 Why are they not opening? 他们为什么不开业? I know passing strings as filenames does not work which is why I thought conversion with c_str() would be sufficient. 我知道传递字符串作为文件名不起作用,这就是为什么我认为使用c_str()进行转换就足够了。

Thanks, Ben W. 谢谢,本W.

Your issue is likely to be due to the path beginning with ~ , which isn't expanded to /{home,Users}/${LOGNAME} . 你的问题很可能是由于与开头的路径~ ,未扩展到/{home,Users}/${LOGNAME}

This answer to How to create a folder in the home directory? 这个答案 如何在主目录中创建一个文件夹? may be of use to you. 可能对你有用。

Unfortunately, there is no standard, portable way of finding out exactly why open() failed: 不幸的是,没有标准的,可移植的方法来找出open()失败的确切原因:

I know passing strings as filenames does not work which is why I thought conversion with c_str() would be sufficient. 我知道传递字符串作为文件名不起作用,这就是为什么我认为使用c_str()进行转换就足够了。

std::basic_ofstream::open() does accept a const std::string & (since C++11)! std::basic_ofstream::open() 接受const std::string &因为C ++ 11)!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM