How to read from a file in C++ (during a GoogleTest) [duplicate] - c++

This question already has answers here:
How do I get the directory that a program is running from?
(26 answers)
Closed last month.
UPDATED:
I am learning about GoogleTest to test C/C++ programs. I heard GoogleTest is a good tool for it. I tried one simple thing, which is to read input from a file, during a TEST() function, and it did not seem to work:
test.cpp in the google test project:
#include <iostream>
#include <fstream>
#include <filesystem>
TEST(IOTest, ReadFile) {
std::string filename = "input.txt";
std::string buffer;
std::ifstream ifs(filename, std::ios::binary);
std::filesystem::path cwd = std::filesystem::current_path();
std::cout << "Current directory path: " << cwd << std::endl;
std::cout << "Current file path: " << __FILE__ << std::endl;
ASSERT_TRUE(ifs.is_open());
}
The resulting test failed. And the output is:
Current directory path: "C:\\Users\\Tong\\source\\repos\\BookLibrary\\Debug"
Current file path: C:\Users\Tong\source\repos\BookLibrary\GoogleTest\test.cpp
Value of: ifs.is_open()
Actual: false
Expected: true
I placed the file "input.txt" under the current directory, which is:
C:\Users\Tong\source\repos\BookLibrary\GoogleTest\Debug\input.txt
but it seems that the program cannot find or open it.
Am I missing something here? I also tried
std::string filename = "./input.txt";
but still no luck in reading the file.
UPDATE: problem solved; everything was correct except that I had placed the input.txt file in the wrong folder. It should be placed in
C:\Users\Tong\source\repos\BookLibrary\Debug
and not
C:\Users\Tong\source\repos\BookLibrary\GoogleTest\Debug

Thanks to multiple comments in the original question, I found the root cause of my problem: I did not find my current directory path correctly.
I thought the current directory path was the project directory of the Google Test project. But it was not true. My current directory path was the other project that hosts my main() function. After knowing this, I placed the file to be read from into the correct current directory path, and the code worked.

Related

How to make a program work regardless of the user's pwd when using file streams?

Consider project in ~/my/computer/my_project with files:
main.cpp
input
We want the project to be usable on ~/your/computer so we use relative paths when dealing with file streams:
// main.cpp
#include <iostream>
#include <fstream>
int main ()
{
std::ifstream stream("input");
if (!stream.is_open())
{
std::cout << "No file detected" << std::endl;
}
stream.close();
}
This works when the user executes the program in the my_project directory, but fails otherwise (prints No file detected, which isn't desired).
How to make a program work regardless of the user's present working directory when using file streams like this?
You need to build a relative path from the location of your executable file.
This depends on the OS, and here are a few ways to do that:
Finding current executable's path without /proc/self/exe

Can' open File in C++ under MacOs

I want to open and read a file in C++. Therefor I wrote the following code:
#include <fstream>
#include <iostream>
#include <string>
...
string line;
ifstream file;
file.open("./db.config");
if (file.is_open()) {
cout << "File is open" << endl;
getline(file, line);
file.close();
}else cout << "File is not open" << endl;
This code is written in the main.cpp. I verified that main.cpp and db.config are in the same directory.
I don't get any Compiletime oder Runtime Errors. It only prints "File is not open". I also tried it without "./" ( file.open("db.config"); ), but this also didn't work.
The problem is, the current working directory is not the one where db.config file is located. You seem to have it in the same directory as the .cpp file. The current working directory is probably something different. Ultimately you need to decide where you want db.config file to reside, there are many options, but here's simple solution:
See where the application binary is.
Copy db.config there if it isn't there already.
In your code, change to that directory before you load the file, which you can do with Qt like this:
QDir::setCurrent(QCoreApplication::applicationDirPath());
Note that if the user runs the program from command line, and are allowed to give files as arguments, then changing working directory inside the program might make those files not be found. In that case, construct absolute path to db.config instead of changing the working directory.
You could read QStandardPaths docs to get better idea on where you actually want to store the db.config file. This depends on how you plan to distribute the application. If you just want to have it in .zip or something, then same directory with application binary is probably fine.

file.open() on linux doesn't open my file, how to solve?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("./cp.txt");
if(file.good())
{
cout << "done!";
}
else
{
cout << "fail";
}
return 0;
}
why does my code can't cp.txt file? it is in project folder. i'm using gnu/linux.
as open i mean the program will open it in some text editor i.e:. leafpad
as open i mean the program will open it in some text editor i.e:. leafpad
That's not going to happen.
When you open an ifstream object it means the file is open for reading by that object, it does not mean a text editor is launched and displays the file!
Maybe what you want is:
system("leafpad cp.txt");
The system function runs another command, in this case it runs the command to launch leafpad with your file as an argument.
Note that the file will be searched for in the current working directory of your program, which is not the same as your "project directory". If you don't know what the current working directory is when your program gets run then you will need to provide an absolute path to the file, not a relative path like cp.txt
you have mentioned having a project folder. if you use an IDE,
it might change the current directory of the running executable.
try deleting the file and creating the file within your code eg:
ofstream ofile;
ofile.open("./cp.txt");
ofile.close();
if you get an output done! then search for the file.

I am having trouble opening a .txt file in my C++ program

I have put it under the Source Files folder. I have set my working directory to $(SolutionDir)$(Configuration)\ (im not sure if that is right, i saw it somewhere) could someone help me troubleshoot.
int main()
{
cout << "program running" <<endl;
pair<int, unsigned int> mypair;
ifstream myfile;
myfile.open("numbers.txt", ios::in);
if (!myfile.is_open()){
cerr << "can't open input file" << endl;
}
else
{
cout << "file opened" << endl;
}
getchar();
myfile.close();
}
...output is: can't open input file
To figure out what directory you're pointing to, try to create a new file instead of opening one:
std::ofstream("out_test.txt");
Then you can find that file searching with File Explorer into the solution dir.
There is such thing as current directory for an application. When you run an app from VS working directory would be current one.
If you specify file name with relative path (or no path at all) OS will try to find that file relative to that directory. Where executable file and especially source file(s) are located completely irrelevant. So solution could be either set working directory to where numbers.txt is located (or move nubers.txt there), or use relative path something like foobar/numbers.txt or even ../foobar/numbers.txt etc or use absolute path.
okay I managed to figure it out..with help :) I did what Paulo M said :
To figure out what directory you're pointing to, try to create a new file instead of opening one:
std::ofstream("out_test.txt");
Then you can find that file searching with File Explorer into the solution dir.
After I figured out where the file got sent I added a new file w/ some integers to that dir and made sure the working directory was the same.I'm not sure if i had to change it? (can files be sent elsewhere?).
I had tried to do this before but I was not able to move my txt file into this directory by copy paste..so gave up. But anyhow I just right clicked/new text document/ and edited the doc with some numbers. then changed my program to open this new document.
saving file directly to the directory also worked. :) :) :)
but i am curious why I couldn't just paste it there?

Trying To Read In File With C++ But Not Working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In the following code I am simply trying to open a file and print it's contents:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
std::ifstream fin;
fin.open("ride");
string line;
while (fin >> line)
{
std::cout << "I am here" << std::endl;
cout << line << endl;
}
fin.close();
return 0;
}
however no matter what I do this program is not entering the while loop....why?
I am running Ubuntu 14.04, the file has the name 'ride', it is located in my home directory and my source file which happens to be 'main.cpp' is also located in my home directory, in addition the cursor is placed at the beginning of the file 'ride'. I have tried changing file name to 'ride.txt' and using absolute paths but nothing seems to work.
It does not matter one bit where your source file is located, as your source file is not being executed.
file must be in the current working directory of the shell from which you've run your program.
Furthermore, if you've tried absolute paths and it still doesn't work then your permissions are insufficient.
There is nothing wrong with the code you've posted.
Probably current working directory of your program is not the directory which contains your file.
To prevent this, you can:
Use path relative to the current working directory. (for example '../src/bar')
Use function chdir to set current working directory at runtime.
Use full path of you file. (for example '/home/foo/Desktop/bar')
If you use development environment, you can set current working directory in options.