Strange (c++) debug issues using VS2013 - c++

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

Related

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

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.

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.

.CPP File and .EXE File With Inconsistant Logic

I've never run into this issue before where when I build my code, the main error checking if statement runs correctly in the console.
ifstream inputfile;
inputfile.open("arrayNumbers.txt");
if(inputfile) //<----- This is working correctly in the CPP, but not in the EXE
{
Unfortunately when I go to run the executable file, that if statement kicks out to the "File not opened" else portion
else
{
cout << "File did not open" << endl;
//^^^^In the exe, the program skips the rest of the code and kicks here
}
Anyone have any clue as to why this is happening?
Compiler is Visual Studio 2010
I have run it in both debug and release mode as well
It is likely to do with where the file arrayNumbers.txt is stored, move the file into the same folder with the executable and it should work.
When you run in Visual Studio the file is running from the Solution folder, when you double click the .exe you run from the Project->Debug-> folder most of the time
You can maybe add a Post Build Event to your project to automatically copy the file to your output dir.
copy $(SolutionDir)/arrayNumbers.txt $(OutDir)

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.