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.
Related
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.
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.
I'm working on assignment for my university. I have a question on how to display all the files contain inside a particular directory. My working environment is on LINUX UBUNTU 14.04 G++ Compiler.
Let's take an example, I want to display/output all the files inside this DIRECTORY
/home/user/Desktop/TEST/FileSystem
File contains inside FOLDER FileSystem
-test.txt
-abc.txt
-item.txt
-records.txt
I'm not sure whether it can be done by using:
-Using Execute System Command, by calling standard library header.
#include <iostream>
#include <stdlib.h>
int main()
{
system("pwd"); // Directory: /home/user/Desktop/TEST/FileSystem
system("ls"); // Display every files contain in the FileSystem Folder
}
OUTPUT that I expected:
/FileSystem Folder contains:
-test.txt
-abc.txt
-item.txt
-records.txt
How can I code my source code so that I'm able to achieving this OUTPUT/Display that I expected. I have go through some internet sources by googling it. But I find out difficulty on understand it. That's why I have made a decision to post my question on here.
Thank You in advance to you guys for helping me to solve my coding problem.
You need to first open directory for which you need to list files after that you need to read directory.
Add #include for using apis.
#include <dirent.h>
/* open the directory "/home/" for reading. */
DIR* dir = opendir("/home/users");
entry = readdir(dir)); //files or directories in /home
//Add logic to verify entry is file or directory
Refer this thread http://www.cpp-home.com/tutorials/107_6.htm
the function
system("ls")
is just firing the command but you are missing what the output of the command ls is.
You need to capture it.
In this other thread it's explained how to do it.
I've got a program that is going to have several resource files that the user can put somewhere on the computer that isn't in the same folder as the executable. How do I get open those files?
I've found lots of answers saying that the reason things aren't working is that the file isn't in the working directory. I've tried providing fully qualified paths:
ifstream str;
str.open("/home/millere/foo.txt")
but that was unsuccessful. I know the path was correct (copy and paste). I can't find any documentation on it, but I assume it has to be possible. (vim ~/foo.txt from anywhere other than ~ works, for example).
Assuming you meant to use ifstream instead of iostream, your code is correct. ifstream can use a path to a file as well as the name of a file in the working directory.
No exceptions are thrown if the file does not exist, but the fail bit is set. You should check for this before trying to do anything with the stream.
std::ifstream input("/home/bob/stuff.txt");
if (!input) std::cerr << "Could not open the file!" << std::endl;
else
{
// ...
}
If you still cannot extract data from the file, the problem is somewhere else in your code.
I had the same issue and quickly noticed that, open when trying to get from a difference folder, had a different source directory (if using Cmake, the one that was specified by the cmake). You can find out, what the ouput/input source directory is by doing
system("ls")
or
system("dir")
on windows to show the content of the current ouput/input directory.
My programs have been running properly for over a year. Today I copied the files onto a different system and compiled every program.
When I compile and run from Dev-c++ it writes data onto a text file like its supposed to, but when I click on the executable it creates, it does not write data onto the file. Everything else like input/output seems to work.
What procedure have I missed?
Ok i've given the program Full permision but it still does not write.
I'm quite puzzled, atleast if it didn't run when i compile it in the C++ environment i can keep checking my code, but only the .exe does not work, any other suggestions ?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream bss2;
bss2.open("expat.txt",ios::app);
bss2 << 2 ;
bss2.close();
}
This is the sample code i tested out.
How do i find the Current working directory ?
Ok i changed a line to
bss2.open("c:\\expat2.txt",ios::app);
and now it works properly in the exe file.
but there's over 50 files and i prefer i didn't have to spell out the new path to each one, what workaround is there to set the directory to the one previously used ?
update 4 :
#define _POSIX_SOURCE
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
char cwd[256];
int y;
if (chdir("/tmp") != 0)
perror("chdir() error()");
else {
if (getcwd(cwd, sizeof(cwd)) == NULL)
perror("getcwd() error");
else
printf("current working directory is: %s\n", cwd);
}
scanf(y);
}
Ok i used the getcwd() and this is the message it gives me
chdir() error(): No such file or directory
How do i set the directory now.
Sounds like your working directory isn't being set correctly when you double-click on the file. If you can access a log, use getcwd() and log what it returns.
I don't have Raymond Chen's psychic debugging powers yet, but I do know of a tool that may help you: Process Monitor. Use it to see precisely which files your application is trying to write to, and why it fails.
Maybe your looking at the wrong location. The program will write the file to the current working directory, which may be different between when you double click on the executable and run from Dev-C++.
The best and easiest way is to give the full path of the output file rather than just the filename. That way, you can be sure where the file went, and not have to search for it everywhere. If you are using Windows, the output file might be somewhere in system32. But I could be wrong.
As others have said, the working directory is likely incorrect.
If you create a shortcut to the .exe, you can set the working directory in the shortcut properties. Right-click on the shortcut, select "Properties", and change the "Start in" property.
Of course a better answer is to put the full path of the file into the filename string when you open it.
It might be that Windows uses backslash, so try "\tmp" instead of "/tmp".
Also if all your files are in the same directory, then you can use find & replace and replace open(" with open("c:\\your_directory_here\