I'm trying to open multiple files to compile the data in them. My program compiles but when I run it i get the following error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
So far my program is pretty lengthy so I'll just link the parts of it that deal with opening the files.
int main(int argc,char *argv[])
{
vector<Plays> yearsEntered;
Plays *MyPlays = new Plays();
if (argc < 2)
{
cout << "No filenames given." << endl;
return 0;
}
for(int i=1;i < argc; ++i)
{
string filename = argv[i];
cout << filename << endl;
filename.append(".csv");
cout << filename << endl;
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
//Error checking in case file fails to open
if (!inputFile)
{
cout << "Could not open file. " <<
"Try entering another file." << endl;
}
}
I'm not quite sure why I'm getting an error but if I had to guess i'd say it was something to do with the fact that argv[i] is a *char array and I'm setting it equal to a string. Also when i run the program it's run like this: ./Analyze 2009 2010 (etc). When i run it it'll print out the name of the file that I want to open so I know the problem is when it tries to open the file itself. This is my first time asking a question so if there's any convention I failed to follow let me know and I'll try to fix it.
You already opened your files once. You don't need to open them again.
The std::ifstream constructor is opening each file, then your invoking .open() for no reason. Remove the inputFile.open() line.
Change this:
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
To this:
ifstream inputFile(filename.c_str());
Related
I'm trying to read multiple files in a folder so I can parse through their data.
I first try to fill the list using a text document with all the file names in it, then based on that vector of string, continuously call ifstream so I can read every file and process the word data.
The problem I'm running into is that ifstream is failing to open all of the files, except one in the middle of the list?
Heres the output, its failing to read the dbfiles but they all have the right names?
These files aren't more than 8GB a piece so it should be able to handle it but it's not?
maybe theres a problem with the file paths?
std::ifstream dbfiles(argv[1]);
if (!dbfiles)
{
std::cerr << "Failed to open database " << argv[1] << " for reading." << std::endl;
}
std::string word;
std::vector<std::string> dbfile_names;
std::string file_name;
while (getline(dbfiles, file_name))
{ //reading in the file names
dbfile_names.push_back(file_name);
}//populate list of dbs
dbfiles.close();
for (unsigned int j = 0; j < dbfile_names.size(); j++)
{ //for every single file
std::ifstream dbfile(dbfile_names[j].c_str());
if (!dbfile)
{
std::cout << "Failed to open database file" << dbfile_names[j] << " for reading. READ FAILURE" << std::endl;
}else{
std::cout << "currently reading " << dbfile_names[j] << std::endl;
}
while (dbfile >> word)
{
//do stuff with the segments of data
//here I gather the data word by word and process it
}
dbfile.close();
}
I went into my debugger and found that due to getline, all the file names had a /r at the back of them.
The post over here Getting std :: ifstream to handle LF, CR, and CRLF?, helped describe the problem and how to easily fix it.
My files are now reading accordingly
i just started reading on how to open and edit files.
when working with ifstream, if the file doesnt exist, it wont be created.
in reference to the code below, when would the condition (!outfile) be false, as if the file doesn't exists it will simply be created by the constructor, hence always making the condition false.
int main()
{
ofstream outfile ("test1.txt");
if (!outfile)
{
cout << "cannot create file test1.txt" << endl;
return 1;
}
outfile << 10 << " " << 345.12 << endl;
outfile << "This is a short text file";
outfile.close();
system("PAUSE");
return 0;
}
One way opening an ofstream could fail is if the file in the given path exists, but you do not have the permission to write to it. Alternatively, if the file does not exist but you do not have permission to create a file in the given path, opening the ofstream should also fail.
Another failing situation could be if the files does not exist, and the underlying device does not have sufficient free space/inodes to create one.
my partner wrote a bunch of code for one of my projects in a text editor, when i run the code it works perfectly.....
now i have copy and pasted all the code into qt creator, and im having an issue
stringstream ss;
string line;
ifstream myfile;
myfile.open("Instructors.txt");
if (myfile.is_open()){
while (getline(myfile,line)){
ss << line << ", ";
}
myfile.close();
}
else cout << "bad open" << endl;
above is the part fo my code that is having the issue, i can assure you all Instructors.txt is indeed in in the correct file, but everytime our code reaches this point imstead of opening the file i get thrown to the else "bad open" why would this be?
It's hard to say what it may be without any error code, what you can do is to improve your error message with something more meaningful (for you and for your customers):
else cout << "Error opening file: " << strerror(errno) << endl;
strerror (see reference) function returns a string for a given error code captured in by errno macro.
Otherwise you can do it much more C++ish using exceptions: first enable them for your stream:
myfile.exceptions(ifstream::failbit | ifstream::badbit);
Then catch them, all together is:
try
{
ifstream myfile("Instructors.txt");
myfile.exceptions(ifstream::failbit | ifstream::badbit);
while (getline(myfile, line))
{
ss << line << ", ";
}
myfile.close();
}
catch (ifstream::failure e)
{
cout << e.what() << endl;
}
Try to rewrite file name, may be it contains characters from different encodings.
double check the working directory, chances are it is in the build folder (where the executable gets dropped)
in QtCreator you can fix this by going to projects and selecting run; there you will be able to set the working directory
So, I am using https://stackoverflow.com/a/298713/1472828 to put an argument "hands.txt" (my agrv[1], which is a file I wanna open) in my command arguments. I have tried both hands.txt and "hands.txt", neither of them worked.
int FileParsing(vector<Card> & v, char * FileName) {
ifstream ifs;
ifs.open(FileName);
if (!ifs.is_open()){
cout << "file cannot be opened." << endl;
} else {
So I use debugger to step through my main:
int main(int argc, char * argv[]){
if (argc !=2 ){
//ErrorMessage();
} else {
...
Debugger tells me that my argc is 2, which is right, but how come every time the debugger just goes to
cout << "file cannot be opened." << endl;
which means the argument just fails at reading it
ifstream ifs;
ifs.open(FileName);
Is there something I missed or I passed the argument in a wrong way?
p.s. The text file was read perfectly from cmd, so it's not the problem of code.
Got the idea from #WhozCraig, while running your program in cmd, the text file is put under debug directory. But if you run it using debugger, you have to put the text file in the same directory with other cpp and h files.
Here's my code.
ifstream readFile;
readFile.open("voltages.txt");
if (readFile.fail( ) )
{
cout << "\nCould not open the file ... check to see if voltages.txt exists\n";
system("pause");
return;
}
string tempString = "";
//readFile.seekg(0, ios::beg);
int idx = 0;
if (readFile.is_open())
{
while ( readFile.good() )
{
getline(readFile,tempString);
cout << tempString << endl;
}
readFile.close();
}
If I move the voltages.txt to c:/, then it works fine, but I have it in the same folder as my .exe right now, and when I set a breakpoint at cout << tempString << endl; it shows up just as "". I'd like to keep it in the .exe if possible. As you can see I tried seeking to the beginning, with no luck. Please help this C++ noob! Thank you!
It might be because you are trying to read a local file when the program requires a link to the file from C:/
You can test this by replacing voltages.txt with C:/pathToVoltages/voltages.txt
I would suggest passing the file to your executable by doing this:
int main(int argc, char argv[]){
ifstream readFile;
readFile.open(argv[2]);
/*Rest of the code*/
This assumes the path to the file is given by the first argument you give to the program as in:
./program pathToFile/voltages.txt
Hope this helps