在C++中使用一个字符串来指定文件路径(将文件存放在文件夹中

问题描述 投票:0回答:3

我正在生成数百个输出文件,希望将它们存储在工作目录下一个名为OUT的文件夹中,而不是工作目录本身。每一个文件的名字都是根据当前的迭代来命名的,比如:out1.txt,out2.txt...等等。(out1.txt, out2.txt...等等)。我看了好久的文档,尝试了不同的东西,但没有成功。 下面是代码。(它是在一个循环中,k是迭代数。

char outname[50];
char filepath[30];
char iter_str[10];
sprintf(iter_str,"%d",k)
strcpy(outname,"out");
strcat(outname,iter_str);
strcat(outname,".txt");
strcpy(filepath,"..\\OUT\\");
strcat(filepath,outname);
file = fopen(filepath,"w");

它不是进入 "OUT "文件夹,而是进入工作目录,并像这样命名。

..\OUT\out1.txt
..\OUT\out2.txt
..\OUT\out3.txt
etc

如果有任何建议,我将非常感激!

我现在意识到,在unix上,我应该用""代替"\"。我已经这样做了,但得到了一个seg故障。当使用"/"时也会出现seg故障。

c++ directory fopen filepath
3个回答
3
投票

如果你使用 提升文件系统库,那么你就不用担心是否要使用 \/ 梳理子路径时。您可以使用运算符 //= 来合并子路径。

using boost::filesystem::path;

path pathname("out");
pathname /= "abc"; //combine
pathname /= "xyz"; //combine
pathname /= "file.txt";   //combine

如果是Windows,那么 pathname 将成为 out\abc\xyz\file.txt.

如果是Linux,那么 pathname 将成为 out/abc/xyz/file.txt.


1
投票

使用单斜线(/),而不是转义的反斜杠(\\). 这应该适用于所有的操作系统(包括Windows从XP开始)。


0
投票

我认为你可以使用std::stringstream来代替strcpy()和sprintf()。

std::stringstream l_strStream{};
#if defined(_WIN32)
    l_strStream << outName << "\\" << iter_str << ".txt";//for filename with path
#elif defined(__linux__)
    l_strStream << outName << "/" << iter_str << ".txt";//for filename with path
#endif // try this , no need to use other libs
© www.soinside.com 2019 - 2024. All rights reserved.