Issue opening file with ifstream in qt - c++

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

Related

ifstream.fail() returns true after open()

Why does fin.fail() return true in the following code?
void loadName(){
int pointer; //holds size of file
fin.open("C:\\Users\\iAMspecial\\Desktop\\Names.txt", ios::app);
if (fin.fail()) {
cerr << "could not open intput file names.txt" << endl;
system("pause");
exit(1);
}
pointer++;
getline(fin,Names[pointer]);
for(int ndx = 0; !fin.eof(); ndx++){
pointer++;
getline(fin,Names[pointer]);
}
fin.close();
counter = pointer;
}
I've been struggling with std::ifstream in this function. I've scouted the other questions and even with all the advice, I can’t seem to get the function working.
A lot of the issues also seem to stem from Visual Studio, however I'm using a different IDE. Apologies in advance if I missed something really stupid.
I've made doubly sure of the file path, it is 100% correct. I'm truly stumped.
Picture of output:
The program is quite long, however if any other parts of it are relevant to the issues I'm having I'm happy to post it.
(Also note that the file path is temporary, I'm merely trying to have the function work, at that point I will have it work with different file paths).
Use fin.is_open() instead. fin.fail() is not for checking stream open errors.
if (!fin.is_open()) {
cerr << "Error: " << strerror(errno);
}
Also, the correct way to read file line-by-line is
std::string line;
while (getline(fin, line)) {
// Do whatever with line
}
Every system call that fails update the errno value.
You can have more information about what went wrong if you will print it:
cerr << "Error: " << strerror(errno);

ifstream not working with variable parameter using C++11 and c_str() appended

Note: I am using the C++11 standard, so I don't see why this isn't working with or without c_str() appended.
I have the following code:
// open streams
ifstream in(input);
ofstream out(output);
// get which file to open
in.ignore(INT_MAX, ':'); // we don't need the beginning part
in.ignore(); // remove trailing whitespace
string fileLocation;
getline(in, fileLocation);
out << "Loading: " << fileLocation << endl;
cout << "Loading: " << fileLocation << endl;
// now that we know where the file is, load it:
ifstream file(fileLocation);
which reads from a file that looks vaguely like this
File: file.txt
(Subcommands below)
I know that I am pulling the correct filename because of the terminal output.
Anyway, I noticed that the stream wasn't opening properly, so I added this conditional to check:
if ( !file )
{
cout << "File wasn't loaded properly." << endl;
}
And sure enough, I see that message when running the program.
My question is this: how come, when I hard-code the file location, e.g. ifstream file("file.txt") it opens up no problem? How do I get this working properly?

Error when trying to open multiple files in c ++

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());

Am I missing something? I keep outputting "No file found!"

void getBookData(bookType books[], int& noOfBooks)
{
ifstream infile;
string file = "bookData.txt";
infile.open(file.c_str());
if (infile.fail()) {
cout << "No file found!" << endl;
infile.clear();
}
while (true) {
string line;
getline(infile, line, '\r');
if (infile.fail()) {
break;
}
cout << "Line: " << line << endl;
}
infile.close();
}
I've tried putting the file in every location I can think of, but somehow it's not loading in. Or, more likely, I'm doing something else wrong. This isn't anything like what the end result of my code is supposed to be like, right now I'm just trying to read out my file line by line.
I guess you really need help debugging why this is happening to you.
Try adding some more code to your routine to help you determine what is going on. One thing to try is to call getcwd.
#include <unistd.h>
...
char buf[PATH_MAX];
std::cout << "cwd: " << getcwd(buf, sizeof(buf)) << std::endl;
...
This should report to you where your program thinks it is running from.
Start with that first, and I am guessing the next steps will become obvious to you.

Simple C++ Writing to File: Nothing Gets Written! Should be easy, but I'm stumpted

Thank you so much for helping me! Everyone is so fast and excellent! Thanks again!
What is happening is no data is being written to my file, after I test this code. Just a 0 appears.
What am I doing wrong?
void CreateHtmlFile(string myMessages[])
{
int i = 0;
int emptyarray = 0;
int myEmptyCounter = 0;
int emptyArrayCounter = 0;
string myEmpty;
ofstream myfile;
myfile.open ("C:\\Users\\Andrews\\Documents\\Visual Studio 2010\\Projects\\computerclass\\Debug\\outages.htm", ios::out);
if(!myfile) // is there any error?
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}
myfile << "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>\n";
myfile << "<html>\n";
myfile << "<head>\n";
myfile << "<title>Livermore Readerboard</title>\n";
myfile << "<style type='text/css'>\n";
myfile << "table {font-family:Helvetica Narrow, sans-serif;font-size:42px;}\n";
myfile << "body\n";
myfile << "{\n";
myfile << "text-align: center;\n";
myfile << "background: #000000;\n";
myfile << "color:#00FF00;\n";
myfile << "}\n";
myfile << "#container\n";
myfile << "{\n";
myfile << "margin-left: auto;\n";
myfile << "margin-right: auto;\n";
myfile << "width: 93em;\n";
myfile << "text-align: left;\n";
myfile << "</style>\n";
myfile << "<META HTTP-EQUIV= \"refresh\" content= \"5;URL=readerboard.htm\">\n";
myfile << "</head>\n";
myfile << "<body>\n";
myfile << "<div id='container'>\n";
myfile << "<table class='Design6' border=1 cellpading=1 cellspacing=0>\n";
myEmpty.clear();
while (i != 10)
{
if (myMessages[i] != "")
{
myfile << "<tr>\n";
myfile << "<td><b>" << myMessages[i] << "</b></td>\n";
myfile << "</tr>\n";
i++;
}
else
{
i++;
emptyArrayCounter++;
}
}
if (emptyArrayCounter == 9)
{
//empty array so insert default message
myfile << "<tr>\n";
myfile << "<td><b>" << "No Outages" << "</b></td>\n";
myfile << "</tr>\n";
}
myfile << "</div>\n";
myfile << "</body>\n";
myfile << "</html>\n";
myfile.close();
}
A few tests to try:
What happens if you send your output to stdout instead of to a file?
What happens if you use a different file path, like "C:\\out.htm"?
What happens if you run this when the file doesn't exist? What about if you manually create the (empty) output file before running the program?
What happens if you simplify the program down to just a simple open, myfile << "test";, close?
What happens if you try to run the abridged version of the program using C-style file I/O (fopen, fprintf, fclose) instead of streams?
[Edit] The need for explicit flush() calls was something I encountered with old, broken, pre-standard compilers like MSVC 6 and earlier over a decade ago. It is probably not necessary any more and apparently was a workaround for problematic library implementations.
I've tried out the code (removing the section to output messages and renaming the output file name to something on my system). The output was correct.
It might be worth trying to write to a local file just to see what happens. You already check for failure to open the file stream for output but there appears to be something odd going on for your case.
[Edit: I'm probably going to get down-voted for being nosy but...] Your C style habits of defining all variables at the top of a given scope are obsolete. Consider defining variables no sooner than where they can be properly initialized and with a more limited scope. It may not be a big deal now, but if you ever work on a C system of any reasonable scale and encounter your first uninitialized variable bugs, you're going to start despising it. Everyone's entitled to their personal preferences, but a style that promotes bugs is an inferior one, objectively speaking.
Your code runs fine on my machine using VS 2005. This expression was giving an error :
myMessages[i] != ""
Converted to
!myMessages[i].empty()
which is better because you are using the string library and method is there to check if a string is empty or not, why not use it.
To check for a stream that was not opened, use:
if (myfile.bad())
The rest looks good, its just that the file path is wrong, or the file cannot be created.