0

我正在生成数百个输出文件,并希望将它们存储在工作目录中名为 OUT 的文件夹中,而不是工作目录本身。每个文件都是根据当前迭代命名的。(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 上我应该使用“/”而不是“\”。我已经这样做了,并且遇到了段错误。使用“//”时也会出现段错误。

4

3 回答 3

3

如果您使用Boost Filesystem Library,那么您不必担心是否必须使用\/同时组合子路径。您可以使用运算符//=来组合子路径。

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.

于 2012-06-12T18:53:36.833 回答
1

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

于 2012-06-12T18:57:05.680 回答
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
于 2020-06-01T10:14:56.537 回答