Open method opens files with full path only C++ - c++

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)

Related

ifstream will not open

The file exists in the directory, and I've tried running Visual Studios in Administrator Mode. However, ifstream can not find the file I give to it.
Here is the code I am using:
std::ifstream instream;
instream.open("appdata.txt");
if (!instream)
{
std::cout << "Could not find appdata.txt!";
}
But I am always greeted with Could not find appdata.txt! when I run the program.
Here is a picture of my directory, for proof that I have it spelled correctly and it exists.
So, my question is, am I missing something so glaringly obvious that I am glazing over it each time I look? I can not figure out for the life of me why instream can not open appdata.txt.
This is a problem with current directory being set to something else than a dir where your file is (usually your home folder if executing from explorer).
Try executing the program from command line from directory where your file is.
EDIT
If you want to set the working directory to some specific location, check this: https://msdn.microsoft.com/en-us/library/aa363806.aspx
Add the file by right clicking on project name on visual studio interface.
This will keep your file in the right directory.
If you want to add in the directory by yourself, first add a file using the method I said above and the find which is the folder you should keep so that you can use that file by mentioning just the file-name. And then you can add your files in that folder.

ifstream can't find file that is saved in the directory

I'm writing a program that uses <fstream>. The file I need to include is called employee.dat and it's listed in the directory. I put in a cout statement that says:
ifstream inFile ("EMPLOYEE.DAT");
if (! inFile)
{
cout << "!!Error in opening 'EMPLOYEE.DAT"<< endl;
}
The file is in the directory and there shouldn't be any issues opening/finding it. This is my first time using the ifstream class.
If you are running from the Visual Studio environment, be aware that your executable probably isn't in the same directory as your data file. Binaries tend to be built into a Debug or Release folder by default. You have several options:
Move your data file into the correct directory.
Set the Working Directory (in your project settings, under "debugging").
Use a full or relative path for your file name.
It's also possible that you are looking in the right place, but the file is locked. Make sure it's not open in any editor or other program that might prevent other processes from opening it.
Beware that in Visual Studio, the Working Directory (set in the project properties under the Debugging tab) is the location that the exe is apparently located when debugging (and not the actual location of the exe itself)

Why can't I read a file with Code::Blocks C++?

I've created a file in Code::Blocks called datos.csv, and I have this code:
std::ifstream file("datos.csv");
if (file) {
cout << "Managed to read file successfully.";
}else{
cout << "Unable to read file.";
}
But it is unable to read the file.
I tested the same code with TextMate, which can run C++ files, and it was indeed able to read the file, so I suppose there's something up with Code::Blocks. What am I missing?
My file appears listed in "Others" in Code::Blocks' navigator.
you need to modify the Target Properties, go to Project -> Properties -> Build targets and change the "Executing Working Dir" for the debug/release folder of your proyect, I hope this help.
Greetings.
Saludos.
It can't find the file to open it. Since you are not using absolute paths to open the file it must be relative to the current working directory. If you are launching from the debugger you can set the working directory used when the application is launched. Make sure that directory is the same as where the csv file is located.

Xcode 4 C++ Project add file to build directory

I'm new to Xcode. How can I add a file to the build output directory? I have a file.txt which I want to open in C++.
The following code...
string line;
ifstream file ("file.txt");
if (file.is_open())
{
while (file.good())
{
getline (file,line);
cout << line << endl;
}
file.close();
}
... results in Unable to open file.
I found out that the executable is deployed to /Users/myusername/Library/Developer/Xcode/DerivedData/IAIK_CMS_Test-dfmszjneldfwjffsmjpmtiepyzej/Build/Products/Debug/
I've tried to add the files in the project settings to the "Copy Files" in the "Build Phases". For details see this screenshot: http://i.stack.imgur.com/QhkIT.png
Edit: I'm looking for something like Eclipse's "add to Build Path" for Java.
Does anyone have a suggestion?
Xcode5 is out, still no answer :)
For Xcode5 in C++ project settings, choose your app target, select "Build phases" tab, unfold "Copy Files" section, set "Products Directory" for Destination, leave Subpath field blank, uncheck "Copy only when installing" and add necessary file (file.txt) to the list using plus sign, like that:
And use "file.txt" path to access your 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.