PDA

View Full Version : ifsteam opening file issue



wildpuma
7th January 2014, 19:50
I have the problem with opening file in Qt using ifstream. Program can`t read data from text document and display on the screen. The same code works in CodeBlocks or other compiliers. I have installed Qt 5.2 Version and created Plain C++ Project. I didn`t try other Version of Qt.
#include<fstream>
#include <vector>
int main()
{
std::vector<std::string> v;
std::string line(""), new_line("");
std::ifstream in("main.cpp");
while(getline(in, line))
v.push_back(line);
for(int j = 0;j<v.size();j++){
new_line += v[j]+"\n";
}
std::cout<<new_line<<std::flush;
}

When I created new test example

std::ifstream myfile("tekst.txt");
if(myfile.is_open())
std::cout<<"Yes!"<<std::endl;
else
std::cout<<"No!"<<std::endl;

The answer of the program was "No". It occured program has no access to file. Maybe someone has the same problem. Should I change settings somewhere?

ChrisW67
7th January 2014, 20:14
Your generic C++ program is attempting to open a file using a relative path, i.e. "main.cpp". Unless the current working directory of the running program is in the same location as that file the attempt to open it will fail.

If you are launching your program from some IDE then you can generally specify the working directory location in the "run settings" of your project. If that IDE is Qt Creator then look here:
http://qt-project.org/doc/qtcreator-3.0/creator-run-settings.html

BTW: Neither Qt nor CodeBlocks is a C++ compiler. Qt is a library and your program does not make use of it.

wildpuma
7th January 2014, 23:30
Thanks;) It highlighted me the problem.