Why can't my program open a file when debugging in VS2013? - c++

This is pretty bare-bones, meant to just get the program going so I can debug the more complex parts:
//open file
cout << "Input File Name: ";
string fileName;
cin >> fileName;
ifstream file;
file.open(fileName, ios_base::in);
if (!(file.good())){
cout << "File Open Error\n";
return 0;
}
The program compiles fine. If I execute the debug executable from \Projects\[this project]\Debug\[program].exe by just double-clicking or browsing there via cmd, it will open the file (which is stored in that same directory) and the rest of the program hums along nicely (until it gets to the buggy parts I actually want to debug, anyways).
However, if I try to 'Start Debugging' from within VS2013, the above fails; it prints the error and immediately closes. The cmd window that the program is executing in when in debugging mode of course shows the directory in the title area, and it is definitely the same directory, but I guess it's looking for the file somewhere else. I tried copying it to the volume root as well, no joy there. I am certain this worked just fine in earlier versions of VS, but maybe I'm just brain-farting here. Any ideas?

In the project properties in Visual Studio, you can set the current directory in which to start the debugged program. By default, this is set to the location of the .vcxproj file, i.e. it's not the location of the executable.
At the same time, relative paths passed to std file stream constructors are interpreted relative to the program's current directory, which is why it fails for you when debugging but not when running directly. If you instead launched the program using these cmd commands:
>cd some\random\dir
>C:\path\to\your\Projects\[this project]\Debug\[program].exe
It would fail in exactly the same way.
To modify the startup directory used by Visual Studio when debugging, go to Project > Properties > Configuration Properties > Debugging > Working Directory. Note that the setting is configuration-specific (i.e. you can have a different startup dir for each configuration). If you want to set it to the directory containing the executable, you can use the macro $(OutDir).
Perhaps preferably, you might want to move the data file into the project source directory, as it's not a build artifact.

Related

Visual C++6 looking for text file in the "solution" directory rather than output directory

I have a VC++6 project and I have the following code snippet:
string s;
int i=0, indx;
ifstream myReadFile;
myReadFile.open("chanmap.txt");
For some reason, when I run the program, it is looking for the text file in the "solution"/root/dsw directory rather than the output directory (i.e. Debug folder) This is a legacy project, so I'm sure that some settings were probably mangled here and there. But this IDE is almost as old as me and very foreign. Any help is appreciated.
For both Debug and Release projects, specify same path in project settings Debugging -> Working Directory:
Other than this, ensure you run the program from Windows Explorer (or command propmpt from the same path). You may need to create a shortcut, where you'd specify directory.
Since you are on Windows, you can also use SetCurrentDirectory within your program.

Strange (c++) debug issues using VS2013

I have inherited a project to work on and the initial build was developed on linux. I dont know if this matters or not but thought I would share it.
In order to debug the project on a windows machine I first use the CMakeGUI on win7 to create a Visual Studio Solutions file to open the project using Visual Studio 2013 and then set the startup project and build the project I am interested in. Up till now everything is okay. Now comes the confusing part.
On load the program is suppose to read a file lets call it in.dat and is declared in const char * inputFileName this variable is then passed through a class which attempts to open then file to obtain data.
fstream fs;
fs.open(inputFileName.c_str(), fstream::in);
if(!fs.is_open())
{
std::cout << "Cannot open input file!" << std::endl;
exit(0);
}
This where I am stumped...the file when placed in the debug folder for some reason cannot be opened i.e fs.is_open() returns false when I try debugging the application BUT if I cd directly into the debug folder of the project, outside of VS, and run the executable it runs as expected i.e fs.is_open() now returns true.
Your debugger's working directory defaults to your project's root directory and the binary is in the \debug subdirectory, resulting, in effect, to the path to the input file being wrong.
Set the debugger's working directory to \debug.
Here is more info on that:
https://msdn.microsoft.com/en-us/library/kcw4dzyf(v=vs.120).aspx

New to Xcode can't open files in c++?

I've been using windows in a class I've been taking but I am trying to run a basic code to figure out how to open/close/input/output from files on Xcode and the code I usually use on visual studios isn't working any idea why? thanks!
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string input;
fin.open("inputFile.txt");
if(fin.fail())
cout << "File failed to open." << endl;
fin >> input;
fout.open("outputFile.txt");
fout << input;
}
Put your .txt files in the same directory where your main.cpp file is (or anywhere you like).
In Xcode go to Product > Scheme > Edit Scheme > Run (on the left) > Options (middle top)
Down under Options for "Working Directory" check “Use custom working directory” and set it to the directory where you .txt files are located.
To work with the files, you will have to specify just file names, e.g. in_file.open("inputFile.txt"); no path is necessary.
Here's a completely different approach: Have Xcode copy the input file for you.
Select your project in Xcode
Select Build Phases
Click the '+' button to create a new Build Phase
Select New Copy Files Build Phase
Select Products Directory
Click the '+' button to add your file
Click Add Other
Select your input file and click Open
Check the Copy items… checkbox and click Finish
Now every time you build your project, the input file will be copied to the same folder as the executable no matter where it is built. Of course, to see the output file, you'll still need to find the executable in Finder.
The answers don't really explain the problem so I thought I'd do that.
When you pass a relative path like "inputFile.txt" to file APIs, it's treated as relative to the working directory when the program is executed. This is the same as the 'working directory' when you use cmd.exe or Terminal.app or command lines in general. The Unix command pwd ("print working directory") displays the current working directory. On Windows running the command cd with no arguments performs the same function. (On Unix running cd with no arguments will change the working directory to the user's home directory.)
When you run a program from the command line, the command line shell sets the program's working directory. When you run a program from within an IDE, the IDE sets the working directory. Since, unlike on a command line, there's no obvious answer for what the IDE should set as the working directory, Visual Studio and Xcode set the working directory to different locations by default: Visual Studio sets the working directory to $(ProjectDir), the directory containing the Visual Studio project file; Xcode sets the working directory to the build products directory, i.e. the location the executable was written to.
Some possible solutions to your problem are:
Do not use a relative path, and therefore don't depend on the working directory. This isn't much help in making the program more portable, because the absolute paths will also differ between platforms, and so you will still have to 'configure' the program for each platform. In fact using an absolute path is worse, because it means your source code must differ, whereas it would be better to keep that difference confined to each platform's build configuration.
Configure the IDE to use your desired working directory. Visual Studio can be configured by right clicking the project, selecting Configuration Properties > Debugging > Working Directory, and setting the working directory to the desired path (potentially using Visual Studio build variables).
nepete's answer describes how to configure the working directly set by Xcode.
Configure the IDE's build process to copy your data files to an appropriate location. In Visual Studio you would do this in a C++ project by configuring the project's Properties > Configuration Properties > Build Events.
SSteve's answer covers how to configure additional build steps in Xcode.
I'm guessing you have inputFile.txt in the folder that contains your source code. That's not going to work. You need to put it in the folder that contains the generated executable. To find that folder, right-click on your app under Products and select Show In Finder.
This image shows what it looks like for a command line program. It also shows the Finder window that was opened. As you can see, it is a different folder than the one containing the source code.
As suggested by nepete, edit the scheme, but use $PROJECT_DIR as the custom working directory. Helps with moving the project around, or working in two different environments (e.g., home and office).
BTW. $PROJECT_DIR is one of the Xcode Environment Variables, and also helps with passing file names as command line arguments to programs (settable under "Arguments" in the scheme).
I've struggled with the same problem today. I wanted to add C code to my Swift project and my file pointer was always NULL.
Unfortunately, in XCode 9 for iOS app, I couldn't change the working directory. Changing Build phases didn't help me either. After 4+ hours of trial and error, that's what I've come up with finally and it works:
when copying files to XCode, I've chosen "Create groups", but I needed to choose "Create folder references":
I created a new objective-c file (.m) and copied all my C code there.
I left untouched .h files (XCode generated bridging header and my own .h file with public functions declaration). Now my project structure looked like this:
In my dict.m file in place of previous plain c fopen part:
FILE *dic = fopen("dictionary.txt", "r");
I added obj-C code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dictionary" ofType:#"txt"];
FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
And it works now without any problem! It's just amazing!
ps I decided to write this answer in case it will help someone like me and will save them some time. If you know how to change working directory in XCode 9 for iOS, please, leave me a comment - now I am really curious why I can't find it.

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)

C++ program infile won't open in xcode?

alt text http://img638.imageshack.us/img638/5731/screenshot20100613at121.png
Why does the c++ program produce the error shown? I'm especially confused since outfile opens without error yet infile displays the error? Both are defined in xcode exactly the same!! I've altering the "path type" setting without success. The open on infile always fails! Any suggestions would be very much appreciated!!
For those who responded thanks but as you can see but infile and outfile exist and are in the same location:
alt text http://img709.imageshack.us/img709/9316/screenshot20100613at123.png
In Xcode, expand the "Targets" node and find your target. Given what I've seen, it'll be the only one there.
Next, right-click on your project and add a new "Copy Files" build phase. When the dialog box comes up, make sure you set the Destination to "Products Directory".
The new build phase will appear beneath your target with whatever name you gave it. Drag your in_file and out_file there.
Compile and run.
In your current case out_file would be created even if it doesn't exist (because you're using std::ofstream).
in_file, on the other hand, has to exist, and (I guess there is no such file in the directory with created binary), hence an error is produced.
Did you try launching your compiled application with the file in the same folder where the binary file is?
Probably there is no file named "in_file" in the program's working directory, so it can't be opened for reading.
For outfile this doesn't matter since it is opened for writing and if it doesn't exist yet it will just be created.
The directory listing you posted doesn't show where the compiled executable is, but probably it will be somewhere in the build directory. Probably this is then also its working directory and the place where the input file would need to be. (Look for the out_file the program creates when it is run, it will be created in the working directory, the same directory where it searches for in_file. And it is not the directory you posted the listing of, the out_file there is too old.)
Turns out you have to specifically create the file here:
Project Path/build/Debug
apparently you can't just define it directly in the xcode project