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.
Related
I'm writing a small game from CS106L course reader. I use Clion and Window.
I put level.txt in the direct location with main.cpp etc. But Why do I need type the full name to read the file rather than just type level.txt?
The core code is:
```c
void readCorrectFile(ifstream& input) {
// Read the user's prompt until user prompt the right file.
while (true) {
cout << "Enter the file name: ";
string filename;
getline(cin, filename);
// Find if it's a valid name
input.open(filename.c_str());
if (input.is_open()) {
return;
}
// Show info about read file.
cout << "Sorry, we cannot find: " << filename << endl;
input.clear();
}
}
```
The output is :
The struct of my project:
Assumedly your current working directory when invoking Snake.exe is not the same as the directory containing level.txt. Programs executed at the command line inherit their current working directory from the shell that executed them.
As Dan said, a relative path should be relative to your .exe file location. In case you build and run your program from IDE, the .exe file is created inside some CLion directories. If you would like to have more control of your .exe file location, you can add the following line to your CMakeLists.txt (before add_executable I assume).
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "path_to_directory_of_your_exe")
This is something I sometimes do for convenience with using relative paths.
I am using Mac and Xcode for my following code which should get my cin value for the name and the age and write them in the file fileProcessingTrial.txt.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
// insert code here...
string name;
int age;
ofstream fileProcessing("fileProcessingTrial.txt", ios::out);
cout<<"Please enter your name: "<<endl;
cin>>name;
cout<<"Please enter your age: "<<endl;
cin>>age;
fileProcessing<<name<<" "<<age<<endl;
return 0;
}
And then where is my file fileProcessingTrial.txt stored (by default?) if I want to open it? Can I store it in a specific location?
I thought I would add an answer specific to Xcode. If you are building and running the executable in Xcode (the IDE), then the output file (if you did not specify an absolute path for the filename) will go to the same directory as the Build Products because that is where the built executable will be. This becomes the current working directory mentioned by Jesper Juhl when Xcode runs the executable. To locate that, click on the product in the Project Navigator (in the below screenshot this is the File Out executable in the left pane). Then look in the File Inspector in the upper right pane. The directory part of the Full Path is where your output file is.
If you did specify a relative path, then the location will be relative to this directory for build products, and as Jesper said, you should avoid encoding an absolute path in your program.
In Xcode, you can also change the current working directory by editing the scheme:
Go to the Options tab under Run in the scheme editor.
Click on the Use custom working directory checkbox
Select or enter the working directory (absolute path)
Hope this helps.
If you do not specify a path (absolute or relative), then the file will be created in the current working directory (aka CWD) of the application at the time you create the file.
A program can change its CWD with chdir() and obtain its current one with getcwd().
It is common for programs to change to some well known directory upon startup and do all their work there if they are daemons.
It is also common for some applications to determine the location of their executable (by reading /proc/self/exe on Linux, for example) and then write files to a directory relative to that.
Other commonly used options are; writing to the users home directory or to a directory specified on the commandline or in a configuration file.
When you run a program from the shell, the CWD will initially be the directory the user was in when starting the application.
When running from a IDE, the CWD is usually set by the IDE to some location specified in its configuration.
In any case, avoid hard-coding absolute file paths in your program, since you can never be certain that path exist on all users machines (exceptions exist of course) nor that the user wants files written there. Best ask the user one way or another and write files to that location.
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.
This is supposed to create a file in my project directory called "tuna.txt". When I run it, it compiles successfully, however no file is created. I am on a mac using xcode. I have searched my computer for other places where it might have been created, but it seems as if the file was not created at all. Any ideas as to why it doesn't work?
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
ofstream file;
file.open("tuna.txt");
file << "I love tuna and tuna loves me!\n";
file.close();
return 0;
}
I assure you that barring errors (which you're not checking for) a file is created. Xcode has a tendency to use the final build-dir as the current working directory when running from the IDE. you can change this by editing the active Scheme.
Click on the Project box to the right of the STOP button on the main toolbar
Select Edit Scheme
Select the "Run" sub scheme in the left pane list.
Select the Options tab,
Check the "Use Custom Working Directory" checkbox
Set the working directory to some place you know (like your project root folder).
Note: This is also where you will setup any command line arguments (those are on the Arguments tab, not the Options tab), should you desire to do so.
In the Products folder (in the Project Navigator of the Navigator tab on the left-hand side of the Xcode IDE) you will find the executable. Click on the executable.
If not already shown, make sure the Utilities tab on the right hand-side of the Xcode IDE is shown and the Show the file inspector is selected.
From the inspector, you will see Full Path showing the path to the executable, and at the end of it, there will be an arrow. Clicking on this arrow will open up the Finder window to that location, and this is where you should also see all the text files and other files that have been created from within the program.
PS. The reason that you couldn't find the tuna.txt file when using the search is because it is in a hidden folder along with the executable.
First of all you must check whether file has been opened/created or not. Then you should search for the file. Most probably the file hasn't been created yet. Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
int main(void){
ofstream file;
file.open("tuna.txt");
if(file.is_open())
{
file << "I love tuna and tuna loves me!\n";
file.close();
}
else
cout<< "No file has been created!\n";
return 0;
}
As you haven't given an absolute path to open function.See the folder where your code file is. Most probably the file will be there.
File opens if I write the full path (full-path/roots.txt).
File fails to open if I write the filename only (roots.txt)
And yet, roots.txt is in the same folder as the main.cpp.
Is there any settings I should check on XCode?
Here's the code:
string line;
ifstream infile;
infile.clear();
// infile.open("roots.txt");
infile.open("/Users/programming/C++/roots/roots.txt");
if (infile.fail()) cout << "could not open the file: " << strerror(errno);
getline(infile, line);
cout << line;
By default, Xcode working directory is something like ~/Library/Developer/Xcode/DerivedData/project-/Build/Products/Debug. So,if you are trying to use a relative path with respect your project directory or any other, you should manually configure your working directory in Xcode.
You can do this by: Product -> Scheme -> Edit Scheme -> options tab, tick the use custom working directory checkbox and show your path.
If it works when you attempt to open a file with an absolute path and fails with just the filename, your relative path is likely incorrect. Ensure roots.txt is placed in the current working directory. Look into the getcwd function declared in unistd.h.
To change the working directory when you're running from inside XCode: select "Edit Active Executable" in your "Project" menu.
You can adjust your working directory settings at the bottom of the "General" section.
Assuming you're running file from within XCode, the working directory is unlikely to be the same directory where your .cpp file is located. Check what your current working directory is what you think it is. (you should be able to obtain it using a getcwd call)