My ifstream doesn't seem to be working
This is a main file that I am using to test methods before I implement them. I am trying to get the list of all files in a directory, write them to a txt file (It works fine until here), then read the file names from that text file.
using namespace std;
string sysCall = "", location = "~/Documents/filenames.txt"开发者_JS百科;
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;
After the program runs, no text has been outputted. From what I've read in other peoples' questions, this should work (but obviously doesn't). What am I doing wrong here?
EDIT: allfiles.good() returns false, but I don't understand why it would return that...
ifstream allfiles("~/Documents/filenames.txt");
doesn't do what you think it does. The tilde ~
character is not part of the filename -- it is a special character interpreted by some shells. You need the entire path, with no ~
or $
characters in it.
Try setting location
to "/tmp/filenames.txt"
, or just "filenames.txt"
.
Also, if Boost.Filesystem is available to you, you could use a directory_iterator
instead of invoking /bin/ls
.
I'll bet the system()
call expands the ~
in the filename to your home directory (e.g. /home/mrswmmr
), but ifstream
does not. Replace the ~
with the full path to your home directory and it should work.
It has no guarantee to work because system
gives no guarantee.
精彩评论