Error reading txt file c++ - c++

I have this code that suppose to read a txt file.
But for some reason i am always getting *File not found that means that fileIn.fail() failed...
#include <iostream>
#include <string.h>
#include <fstream>
#include <sstream>
#include <stdio.h>
using namespace std;
int main ()
{
string fileName;
ifstream fileIn;
bool x;
cout << "enter file name \n";
cin >> fileName;
fileIn.open(fileName);
if(fileIn.fail())
{
cerr << "* File not found";
return true;
}
the file located in the same folder as my main.cpp file and named input.txt. I have tried to set the fileName hard coded but this also didn't work.
What is wrong with my code?
here is the project:

Here is a checklist:
Do you have permissions to read/access the file?
Are you the owner of the file?(Linux)
Are you giving the correct path, relative or absolute from the executable?
If the answer to any of these is a no, then that is where the problem lies, not just "file not found" error.
--EDIT--
#VladIoffe the executable I see there, is qustion2 and the relative path you have to give is ../input.txt and not input.txt

You should use absolute path to the fileName.

Absoulut path will always works. But I hate full path I prefer relative path for a simple reason: code is more portable.
If you run your program with input.txt in the same path of executable it will work. But when you use an IDE you must set the current directory in the IDE settings.

Related

Why could file not be opened using ifstream?

I'm trying to create a simple terminal program that generates random Japanese Gojuōn. I have a source file, named "source", which looks something like this:
A I U E O
Ka Ki Ku Ke Ko
...
あ い う え お
か き く け こ
...
Now, I'm trying to read each line of content into a string variable, and print it out onto the screen, but I was not able to open the file. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream source ("source");
string line;
if (source.is_open())
{
while (getline(source, line))
{
cout << line << "\n";
}
source.close();
}
else cout << "Unable to open file!\n";
}
When I ran the code on terminal, I got "Unable to open file!". The code was in the same directory as the source file.
Are you running from inside your IDE? This is a very common thing when using an IDE.
The current working directory when running from the IDE may not be what you think it is. Try changing the path to the file to be the absolute path so you KNOW it's finding it.

Why won't header file change the contents?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream archivo("saludos.txt",ios::in|ios::out); // Abrir y Leer
char caract;
int cont=0;
while (!archivo.eof())
{
archivo.seekg(cont,ios::beg);
caract=archivo.get();
if (caract=='A')
{
archivo.seekp(cont,ios::beg);
archivo<< 'O';
}
cont++;
}
archivo.close ();
}
i'm using this code but when i build and run it, nothing happens in the file saludos.txt There isn't even a response on the console application. anybody know why? i'm using codeblocks and i also have #include fstream
I tried your code in my environment and it works just fine, it replace all 'A' characters with '0'.
I think your problem is with Codeblocks, if you create a new project and want to use file with the relative path in your project, you have to go to Project -> Properties -> Build targets and change the "Executing Working Dir" to your project's folder.
Or you cant try with a absolute file name with full system path first.

Failed to read .txt file in C++

I have a .txt file and I tried using the absolute path "C:\Users\(full path)\A3Data" and static paths (shown in code):
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream MyReadFile("A3Data.txt");
if(MyReadFile.is_open()) //checks whether file is being opened
{
while (getline(MyReadFile, line)) //uses getline to get the string values from the .txt file to read line by line
{
cout << line << '\n';
}
MyReadFile.close();
}
else if (MyReadFile.fail())
{
cout << "A3Data.txt failed to open" << endl;
}
return 0;
}
Expected output:
(contents in A3Data.txt)
Actual Output:
"A3Data.txt failed to open"
Double backslashing the absolute path e.g. C:\\Users\\(full path)\\A3Data.txt gives me the error too.
Changing the filepaths and ifstream-ing it to the different path also shows me the error.
When i tried to read my file from cmd, I cd'ed it to the full path and typed in the text file name. I could open & read it properly. Hence I feel that the w.r.x are accessible to me and I have rights to the file.
UPDATE:
I have figured out my issue. Thank you all for the answers!
You need to double backslash or declare your file path as a string literal. You can do this like:
string myPath = L"C:\Users\(full path)\A3Data.txt";
As a string literal, or
string myPath = "C:\\Users\\(full path)\\A3Data.txt";
As a properly escaped file path
If the above does not work and you have guaranteed that you have the proper paths to the file then you may not have proper rights to the file. You could try running a command line as administrator and then executing your code from that, if that also fails let us know.

ofstream: cannot open the file

I face an ofstream problem and the program cannot open the file that I want to write. The minimal, complete and varifiable code is showed as follows:
#include <cstdio>
#include <fstream>
using namespace std;
int main(){
string root_path = "E:\\160818\\";
string file_path = root_path + "haar_data.txt";
ofstream haar_file(file_path.c_str());
if(!haar_file) // < -------- File cannot be open
{
cout<<"Error opening file for writing\n";
return 1;
}
haar_file.close();
return 0;
}
My compiler is VS2008. The output in the screen is
Error opening file for writing.
What is the error? I want open this file to write something.
I have compiled your code and used it, it worked.
Note that you haven't included iostream in your provided code therefore I had to add it because of the 'cout' expression.
Note that since c++11 you don't need to use .C_str() to open a file.
Note that if your file doesn't exist, because you use ofstream (opens with ios::out), your file will be created anyway.
Are you using admin rights?
Is your path correct (folder name mistake?)

Cannot open file with relative path? (C++ ifstream)

I know this seems like a simple question, but I tried everything I can think of to no avail to something that shouldn't have been a problem in the first place.
This is a small C++ program that opens a file. When I open it with its absolute filepath, it works fine. With a relative path, however, it stops working.
Here's the file path of the program and the files I'm trying to read:
C++ program: "/Users/Baggio/C++/Lab0/Lab0/Lab0/main.cpp"
Files: /Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt, /Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt
Here's the code snippet:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
int main(int argc, const char * argv[]) {
// string dict_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/dict.txt";
// string result_filename = "/Users/Baggio/C++/Lab0/Lab0/Lab0/result.txt";
string dict_filename_string = "dict.txt";
string result_filename_string = "result.txt";
const char* dict_filename = dict_filename_string.c_str();
const char* result_filename = result_filename_string.c_str();
// open files
ifstream dict_file(dict_filename, ifstream::in);
ifstream result_file(result_filename, ifstream::in);
if (!dict_file || !result_file) {
cerr << "File could not be opened." << endl;
exit(1);
}
}
Result of execution
File could not be opened.
I'm sure I've done all the includes right, and the data types right for the ifstream constructor arguments. The only thing I can think of worth mentioning is the system I'm on: I'm on a Mac and I'm using XCode6 as my IDE.
Also, I've tried to move the files' location (results.txt and dict.txt) to these locations to no avail:
/Users/Baggio/C++/Lab0/Lab0/Lab0/
/Users/Baggio/C++/Lab0/Lab0/
/Users/Baggio/C++/Lab0/
/Users/Baggio/C++/
Thanks for your help guys!! Any suggestions or thoughts appreciated.
Print out your current working directory when you run the program:
char buffer[256];
char *val = getcwd(buffer, sizeof(buffer));
if (val) {
std::cout << buffer << std::endl;
}
This will tell you where you are running your program from and thus why the path doesn't match for relative paths. A relative path is relative to the current working directory, not to where your binary is located.
If you want to make the path relative to the location of the binary then you will have to do that yourself. Many programming languages offer this as an option, but it is not built-in to C++. You can do this by finding the executable using the argv[0] from main. Then you need to drop the file component of the executable path and replace it with the file name that you are interested in.
Since C++17, you can use std::filesystem::current_path() instead of getcwd.
std::cout << std::filesystem::current_path() << std::endl;