我正在生成数百个输出文件,并希望将它们存储在工作目录中名为 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 上我应该使用“/”而不是“\”。我已经这样做了并且遇到了段错误。使用“//”时也会出现段错误。
最佳答案
如果您使用 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
。
关于c++ - C++中使用字符串指定文件路径(将文件存放在文件夹中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002821/