使用字符串在C ++中指定文件路径(在文件夹中存储文件)

时间:2012-06-12 18:42:11

标签: c++ directory fopen filepath

我正在生成数百个输出文件,并希望将它们存储在工作目录中名为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上我应该有“/”而不是“\”。我已经这样做了,并且遇到了一个段错误。使用“//”。

时也会出现seg错误

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

答案 2 :(得分: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