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.
Related
Before you flag this as a duplicate post and refer me on how to correctly open a text file and print to the console, I have looked at numerous StackOverflow posts about this topic and cannot find a solution for myself.
I am trying to open a text file I created (currently in the same project folder as my main.cpp), read the text, and print it to the console. I go through the if file is open statement fine but the while loop does not go through even once. I will post the function below. Please suggest any changes or ideas on how to correctly call and open/read the text file. (and I would prefer not to call the exact file location of the text file for this to work ex. C://example/textFile.txt/ Though I have not tried this method yet, I'd prefer avoiding it)
Also, I am using CLion IDE from jetbrains, C++17, and Ninja to build.
printing text file to console fucntion
#include <iostream>
#include <iomanip>
#include <iomanip>
#include <fstream>
#include <string>
#include <stdlib.h>
#include "printTest.h"
void printTest::print() {
std::string line; //string that holds the line of a text file
std::ifstream textFile("test.txt", std::ios::in); //file creation
if(textFile.is_open()) //checking if file was opened
{
while(std::getline(textFile, line))
{
//std::getline(textFile, line);
std::cout << line << "\n";
}
} else { //this is always printing i.e. file is not correctly being opened for reading
std::cout <<"Unable to open the text file..." <<std::endl; //Prints if file was not opened
}
textFile.close();
}
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.
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;
I am simply trying to get a program to write "Test" to a created file. However, when I run the code below there is no file in the working directory. I am running this code on a Mac and compiling using gcc from Terminal.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example-1.txt");
if (myfile.is_open())
{
myfile << "This is a line.\n";
myfile << "This is another line.\n";
if (myfile.fail())
cout << "Fail" << endl;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
All the code I posted is valid and works. However, I was compiling via the command line on a Mac OSX using gcc. The command looks like this:
g++ -g nameofinputfile.cpp -o nameofoutput.out
This works fine, however when you open the .out file (compilation file) the example-1.txt file is created at the root of the Users file where Documents, Desktop, Downloads etc. exist. Simply you just have to state where it is to be created. Refer to this question to learn how to specify the directory in your code.
You must use of fprintf() for write text on text files.
For example :
fp1=fopen("report.txt","a+");
fprintf(fp1,"Port is open: %d\n\n",i);
fclose(fp1);
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.