C++ ifstream throws file not found even though the file exists - c++

I am trying to open a file where the file path is taken as a user input.
However, the C++ runtime says that the file does not exist, but when I hardcode the string, I am able to open the file.
std::shared_ptr<Task> Daemon::create_new_task(string &location){
std::ifstream file;
std::cout<<"Create new task->"<<location<<endl;
file.open(location.c_str(), std::ios::in);
if (!file.is_open())
perror("Error");
boost::filesystem::path f("<filepath>");
std::cerr<<boost::filesystem::exists(f);
std::stringstream buf;
buf << file.rdbuf();
return std::make_shared<Task>(location,buf.str());
}
perror() says file not found, while the second output is 1.
I tried absolute and relative paths. None of them work.
Any thoughts on this?

Related

Why SFML isn't able to load an image. SFML, C++ [duplicate]

ifstream myfile;
myfile.open("FileTest");
string line;
if(myfile.is_open())
{
cout<<"Reading from file...";
getline(myfile,line);
}
if(myfile.fail())
{
cout<<"Unable to open file"<<endl;
}
myfile.close();
C++ tries to open the file in the current directory with the exact name FileTest. Check to see if the file is in the current directory? Maybe you spelled the name incorrectly? Maybe you forgot to write FileTest.txt? You are using ifstream, which will fail if the file you're trying to open does not exist or is corrupted.

Input Output with fstream

Can anyone tell me what is wrong with this code? I always get not open.
#include <iostream>
#include <fstream>
using namespace std;
int main(){
fstream fs;
fs.open("fsfile2",ios::in|ios::out|ios::binary);
if(fs.is_open()){
fs.write("wow",sizeof("wow"));
char str[20];
fs.read((char*)str,sizeof(str));
cout<<str<<endl;}
else
cout<<"Not open\n";
return 0;
}
Try this code
fs.open("fsfile2", ios::app|ios::in|ios::out|ios::binary);
By using the open() like you are that file will not be created if that is your goal.
If you want to create a new file please look at: fstream won't create a file
If the file exists, you are not looking for it in the right path. Or change the file name to the full path or put the executable in the folder where the file is.
Hope this helps.
Probably, you do not have permissions to create files in the directory, where your executable is.
Solution:
Please add a file extension to the filename.
If it's a text file, it will be
"fsfile2.txt"
Then, I tried removing
ios::in
since the first process only writes to file, and by removing that, the file is created and "wow" is also written at it.
In order for these lines
fs.read((char*)str,sizeof(str));
cout<<str<<endl;
to work,
You need to close the stream after writing to it, then open the stream in read mode, then read the contents. Take note that closing the stream will save the edited file.
Additional:
You can also change
fs.write("wow",sizeof("wow"));
to
fs << "wow";
You can do the same when reading from file,
fs >> str;
You can also use the string class of C++, instead of char array so that the number of characters inside the file won't be your problem anymore.
#include <string>
string str;
Checking for EOF (end-of-file) is recommended since files are read line by line. Once you add a new line and add a character to the line, the code that doesn't loop until EOF will only read the first line of the file.
In order to solve this, it is recommended to loop until EOF is reached.
while(!fs.eof()) {
fs >> str;
cout << str << endl;
}
So here is the improved snippet:
#include <string>
fs.open("fsfile2.txt", ios::out); // ios::out for write only
if(fs.is_open()) {
// writes "wow" to file
fs << "wow";
// closes the file
fs.close();
// ios::in for read only
fs.open("fsfile2.txt", ios::in);
// better to define variable just before using it
string str;
// loops until end-of-file
while(!fs.eof()) {
// reads a line from file, stores it to str
fs >> str;
// shows str to screen
cout << str << endl;
}
}
*Note: I removed
ios::binary
Since your code is not dealing with binary files yet.
I tried these and it worked fine! Have a nice day!
fstream fs; does not create a new file for you.
You need to make sure that the file exists in your project directory.
On the other hand, if you were to use ofstream fs("file.txt"); it would create the file for you. Or use only ios::out when you open fstream fs, this will create the file for you.

fstream is not writing anything on the file

I'm trying to write some things to a text file but it won't even create the file. I will appreciate a lot if you can help me with this. Thanks.
#include <fstream>
#include <iostream>
int main(){
std::ofstream file;
file.open("path/to/file");
//write something to file
file << "test";
//printing to screen
std::cout << file.rdbuf();
//closing file
file.close();
return 0;
}
The following line is your culprit:
std::cout << file.rdbuf();
You cannot use rdbuf to output a file that was opened for write operations only.
Remove that line and your file will be written correctly.
If you want to read your file after you've finished writing to it:
Solution 1:
Open file for both read and write operations using fstream:
std::fstream file("path/to/file", std::ios::in | std::ios::out);
// ... write to file
file.seekg(0); // set read position to beginning of file
std::cout << file.rdbuf();
Solution 2:
Create a new std::ifstream to read from file:
// ... write to file
file.close(); // call `close` to make sure all input is written to file
std::ifstream inputFile("path/to/file");
std::cout << inputFile.rdbuf();
salesFile.open("C:\\Users\\Tebsan\\Desktop\\Coding\\c++\\re\\salesFile.txt"); // ...try to open existing file
if( !salesFile.is_open() ) // ...else, create new file...
salesFile.open("C:\\Users\\Tebsan\\Desktop\\Coding\\c++\\re\\salesFile.txt", ios_base::in | ios_base::out | ios_base::trunc);
You have to call fstream::open with an explicit openmode argument of
ios_base::in | ios_base::out | ios_base::trunc
Otherwise open will fail due to ENOENT.
Thanks for the help!!!
I Learned new things from this. The funny thing is that the issue was the name of the file, apparently the name was too long, and for the new file that included file stream I just added stream at the end of the name, so the compiler kept running the first file (without file stream)...

ifstream failing to open

I am using Visual Studio 2013
So I have to open a .ppm image file and do some work on it, but the ifstream I'm trying to use to read the data fails to open the image file. I am pretty sure the image file is in the working directory (I have created and read some simple .txt files to make sure). And even after excessive research I can't figure out what is going on.
Here's the relevant code
EDIT: I added some more code to get an idea of what I'm trying to do
Image * PPMImageReader::read(std::string filename){
std::string line;
int width, height, max_val;
std::ifstream src(filename, std::ios_base::binary);
if (src.fail()) { //failbit is always set but not badbit
perror("Logical error on i/o operation. failbit was set\n");
if (src.bad())
perror("Read/writing error on i/o operation. badbit was set");
}
if (!src.is_open()) { //and of course this return true
printf("File was not opened\n");
exit(1);
}
//Edited
getline(src, line, '\n');
if (line.empty())
getline(src, line);
if (line.find("P6") == std::string::npos) {
printf("wrong format\n");
exit(1);
}
As from discussed came to know the problem is relative path.
fstream support relative paths as below..
Consider the following case where your input file is one level up than exe file.
E:\MyProgramBin\YourExe.exe
E:\YourInputFile.ppm
In this case, you can create your filename as below.
filename1 = "..\YourInputFile.ppm"
and use that filename1 in ifstream
std::ifstream src(filename1, std::ios_base::binary);

Cant open file using c_str() in linux

On Windows, I have no problems opening the file from string. On Linux (where it needs to work) I can't open the file.
string name;
//open 1st file, with the next file name - this works
fstream file( "data.dat", ios::in);
if(file.good()){
getline(file, name);
//some code here
file.close();
}else{
return 1;
}
// this here does not work
fstream file1(name.c_str() , ios::in);
if(file1.good()){
//some code here
file1.close();
}else{
cout<<"can't open file"<<endl;
return 1;
}
If instead name.c_str() I write the file name directly it works, but every try on getting the name from the file ended with the file not opening.
I've tried creating const char* from name, doesn't work too.
The file probably has Windows-style line endings. Either sanitise the file, or check for and remove any carriage-return character, \r, at the end of each line.