这是我在实现方法之前用来测试方法的主要文件。我正在尝试获取目录中所有文件的列表,将它们写入一个 txt 文件(直到这里都可以正常工作),然后从该文本文件中读取文件名。
using namespace std;
string sysCall = "", location = "~/Documents/filenames.txt";
string temp = "";
sysCall = "ls / > "+location;
system(sysCall.c_str());
ifstream allfiles(location.c_str());
allfiles.good();
getline(allfiles, temp);
cout<<temp<<endl; //At this point, the value of temp is equal to ""
return -1;
程序运行后,没有输出任何文字。从我在其他人的问题中读到的内容来看,这应该有效(但显然无效)。我在这里做错了什么?
编辑:allfiles.good() 返回 false,但我不明白为什么它会返回...
最佳答案
ifstream allfiles("~/Documents/filenames.txt");
并不像您认为的那样。波浪号 ~
字符不是文件名的一部分——它是一些 shell 解释的特殊字符。您需要完整的路径,其中没有 ~
或 $
字符。
尝试将 location
设置为 "/tmp/filenames.txt"
,或者只是 "filenames.txt"
。
此外,如果 Boost.Filesystem可用,您可以使用 directory_iterator
而不是调用 /bin/ls
。
关于c++ - 我的 ifstream 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6311042/