Code runs perfect in g++ but not in Xcode - Cannot find File - c++

I have created a text file with content. It is located in the same folder as the cpp files. And I have confirmed several times that the file exists. When I run g++, compile and run it finds the file. When I run it in Xcode, it does not work. If fails to find the file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

Your file fails to open because XCode launches from the IDE in the default build location, which is actually a temporary directory off somewhere on your disk. If you want change the working directory at launch-time to something else (like the location where your files can be found):
Select the Product/Edit Scheme... menu option.
Select the Run schema in the left list.
At the bottom Options tab on the right pane should be a "Working Directory" option. Check the checkbox and set the custom working directory to someplace you know (your "/Users/yourname" home directory is a decent place that I use).
Make sure any "current directory" data files you need for your program execution from the IDE are in this directory.
And in case you didn't see it, this is also the place where you can configure command-line arguments (on another tab) of the same dialog.

Try to add files to the project in XCode or use the absolute path instead.

Related

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.

Making Log File

I'm trying to create a log file using the code below, but It's not working and I'm unable to get the logs as the file is not created!
#include <iostream>
#include <fstream>
using namespace std;
ofstream myfile;
int main () {
myfile.open ("example.txt");
if (!myfile.is_open())
{
cerr << "Failed to create Log" << endl;
}
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
For me, it is working fine. compiled with g++ on ubuntu.
If your are using linux, try locating example.txt as may be the working directory is different. In windows, you can search for the file in your computer.
I managed to get your code working, as it worked out of the box. Files created adhere to an odd structure, so you'll need to put your assembly version as a prefix either through a define or a variable.
You can find example.txt up a directory from Debug/Release, next to your .vcxproj file, and in the folder next to your .sln file.
Tinkeroonie is the name of my project, yours might be LoggerTest or something like that.
Highlighted is the folder you need.

Why isn't my file opening, C++? XCode and Visual Studio

This is happening in both Visual Studio and XCode
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream input;
input.open ("matrices.txt");
if (!input.is_open()) {
cout << "not open!";
} else {
cout << "open!";
}
input.close();
return 0;
}
My file is not opening. The text file matrices.txt is in the same directory.
What is "same directory" in this context?
For a file to open like this, it has to be in the working directory of the executable when run in the debugger.
For Xcode; this means adding the files to the Copy Files build phase (accessible by editing the executable's target); and adding it to the Products Directory, selected from the dropdown.
In Xcode if you want to work with a file you have to put it in a folder called DeriverData. You can navigate to it by doing the following:
Xcode > preferences > click on Locations.
this brings up the following window
you can click on the small arrow to the right of the path: /Users/dulybon1/Library/Developer/Xcode/DerivedData
It will open the directory containing a list of all your Xcode projects. Find your project and navigate to: build > products > debug
as seen below:
Then you can put your files there. "a1.txt" and "a2.txt" are files that I have put there to work with. And I think the file needs to exist before it can be opened, so just create blank files if you are planning of using them. Hope that helps

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.

C++ ifstream on XCode: Where is the default directory?

Ok, so this is the first time I've coded C++ in Xcode (I'm used to ObjC)and I've now started a programming course at my college.
I'm trying to open a file (either hard coded or from user input in the console) and no matter what I try, it says the file won't open (through error checking)
I'm assuming it's because the test.txt file I have isn't in the assumed root directory, so if that's the case, what is the root directory?
Here's my code so far:
//include files
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
//Global Variables
short inputPicture[512][512];
short outputPicture[512][512];
//Function Prototypes
void getInput(char* in, char* out);
void initializeArray(ifstream* input);
//Main
int main(){
//local variables
char inputFile[32];
char outputFile[32];
ifstream input;
ofstream output;
getInput(inputFile, outputFile);
cout << inputFile << endl;//test what was sent back from the function
input.open(inputFile, ifstream::in);
if (!input.is_open()){//check to see if the file exists
cout << "File not found!\n";
return 1;//if not found, end program
}
initializeArray(&input);
return 0;
}//end Main
//Gets initial input from user
void getInput(char* in, char* out){
cout << "Please designate input file: ";
cin >> in;
cout << "\nPlease designate an output file: ";
cin >> out;
}//end getInput
//Sets the global array to the information on the input file
void initializeArray(ifstream* input){
}//end initializeArray
Please let me know if there's something else wrong I'm doing, as I'm sure that's always a great possibility :)
The default directory should be relative the application's working directory, which is usually the same place the application is located (debuggers can mess with that, sometimes).
For simple testing, just specify an absolute path in the command line (or code).
To get the current directory (to see), the getcwd() C function (also usable in C++) will help. Something like:
char * dir = getcwd(NULL, 0); // Platform-dependent, see reference link below
printf("Current dir: %s", dir);
That should display it in the console. The getcwd function has a few variations depending on what you run on, I've not tested on Mac, but info here:
http://linux.die.net/man/3/getcwd
In the Xcode (v7.1.1 at the time of writing) sidebar, there's an automatically generated folder called "Products". Inside you'll find the executable of your project (assuming you've built your project at least once). Right-click it & choose "Show in Finder". A folder will open in Finder. That's the working directory of your program, & you'll notice it's not actually inside your project's folder.
You can have Xcode use a different directory instead. In the top toolbar, on the left side where it shows your project name next to the active build architecture, click on the Project name > Edit Schemeā€¦
Then look for an option called "Working Directory" in the sheet that appears. Tick the checkbox & then choose a custom directory. Note: Make sure the "Run" option is the selected one in that sheet's sidebar.
The "root" directory that your executable is looking for the file in is not the actual / root directory of the file-system, but is the directory that the executable is executing in ... if you are using Xcode, this may be buried inside one of the build directories automatically created by Xcode for your project rather than a user home folder or home folder sub-directory like /Users/XXXXXX/Documents.
The "default directory" is the directory from which the executable was executed. Usually this is in the same folder as the executable, although if you do stuff like dragging and dropping files on an exe, it can change the startup path.
The path can also change if you're running the program from inside your IDE. The IDE starts the executable, so there's no telling where it's doing it from. You'll have to find where it stores executables and put the file in there, or use an absolute path.
In my case,
- getcwd(NULL, 0) returned "/".
- and couldn't use abusolute path.(It changes on each terminal deployed.)
So I got the path by ObjC code and throw it to c++ function.
1.Put files in top directory of xcode project. And check they are included in "Targets"->"Build Phases"->"Copy Bundle Resources".
2.Get the path by ObjC code.
NSBundle* bundle = [NSBundle mainBundle];
NSString* resourceDirectoryPath = [bundle bundlePath];
NSString* path = [resourceDirectoryPath stringByAppendingString: #"/"];
3.And throw it to c++ function.
[self cppFunc:[path UTF8String]];
4.Then you can make an ablsolute file path in c++.
std::string file = path(arg) + "filename";
It worked for me.