Path to input files in VS 2019 - c++

Visual Studio does not seem to be finding input files when I try to compile under "Debug":
/* in.dat exists in
\ProjectName\
\ProjectName\Debug\
\Debug\
*/
string name = "in.dat";
ifstream ifs(name); // nullptr...
Are there specific places VS looks for input files? Specifying an absolute pathname did not solve the problem.

There is a setting in the current project settings for working directory.
When you build a project in visual studio, the executable is run in this directory, regardless of which directory the executable is in.
The working directory is found under Project Settings >> Configuration Properties >> Debugging
More information about properties pages:
https://learn.microsoft.com/en-us/cpp/build/working-with-project-properties?view=vs-2019

Related

Calling MATLAB Engine error: libeng.dll is missing from your computer

I am struggling to call MATLAB from a simple .cpp program despite the many resources online for this problem.
My Objective:
Use Microsoft Visual Studio 2010 Professional 64-bit to build .cpp program that
calls MATLAB Engine for built-in functions and graphs (MATLAB R2013b 64-bit)
What I have done:
In the .cpp file property pages, I have:
1) Changed the platform to Active(x64)
2) Added the following paths to the VC++ Directories
Executable Directories: C:\Program Files\MATLAB\R2013b\bin
Include Directories: C:\Program Files\MATLAB\R2013b\extern\include
Reference Directories: C:\Program Files\MATLAB\R2013b\bin\win64
Library Directories: C:\Program Files\MATLAB\R2013b\extern\lib\win64\microsoft
Path Edits
3) Wrote the following program:
// mEng.cpp : Defines the entry point for the console application.
// libeng.dll is in C:\Program Files\MATLAB\R2013b\bin\win64
#include "stdafx.h"
#include <Engine.h>
#include <matrix.h>
#include <iostream>
#include <string>
#include <cmath>
#pragma comment (lib, "libmat.lib")
#pragma comment (lib, "libmx.lib")
#pragma comment (lib, "libmex.lib")
#pragma comment (lib, "libeng.lib")
#pragma comment (lib, "libut.lib")
using namespace std;
int main()
{
Engine *m_pEngine;
if (!(m_pEngine = engOpen("")))
{
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
//Now call the MATLAB script through MATLAB Engine
engEvalString(m_pEngine, "script");
cout << "Hit return to continue\n\n";
fgetc(stdin);
//Close the MATLAB Engine
engClose(m_pEngine);
return EXIT_SUCCESS;
}
Errors received:
“The program can’t start because libeng.dll is missing from your computer. Try reinstalling the program to fix this problem.”
I faced the same problem and spent one day to solve it.
So here is my answer.
Actually you overdefine different directories (see the "Path Edits" link).
It is enough to made just these:
Project Properties -> VC++ Directories -> Library Directories. Add here path C:\Program Files\MATLAB\R2016a\bin\win64 (version and path can differ, but the idea is to est path to the same folder of your MATLAB)
Project Properties -> C/C++ -> General -> Additional Include Directories. Add path C:\Program Files\MATLAB\R2016a\extern\include (your path of this folder)
Project Properties -> Linker -> General -> Additional Library Directories. Add path C:\Program Files\MATLAB\R2016a\extern\lib\win64\microsoft
Project Properties -> Linker -> Input -> Additional Dependencies. Add here: libeng.lib; libmx.lib;
And the last and the most important: add the path of MATLAB Engine dll libraries to your Windows. This step solve your problem. We can do it this way: My Computer -> right click: Settings. Opened window System. Left bottom corner: Advanced System Settings
Advanced Tab
In the Environment variables for your user press Create... button and add this one:
Variable name: PATH
Variable value: C:\Program Files\MATLAB\R2016a\bin\win64
This path is reference on where is your libeng.dll located.
Important moment: it can require to restart VS or even restart computer.
Hope it helps some people, who start to work in MATLAB and C++!
Follow my notes here:
https://www.mathworks.com/matlabcentral/answers/100603-how-can-i-compile-a-matlab-engine-application-using-microsoft-visual-studio-9-0-or-10-0
I would like to take this opportunity though to re-format the instructions given there:
To compile a MATLAB engine application in the Microsoft Visual Studio 9.0 (2008) or Microsoft Visual Studio 10.0 (2010) environments, perform the steps outlined below:
Open Microsoft Visual Studio and select
File->New->Project
and then select:
Visual C++ -> General -> Empty Project
Following this, enter the name of the project and its location in the
indicated text areas and click OK.
Note be very careful with this step as it will create the solution folder and
put a project folder in there, so you won't want to set this up, get it all
working and then change the folder as that will break the solution and you'll
have to start all over.
Right-click on the SOURCE FILES folder in the SOLUTION EXPLORER and click
Add -> "New Item..."
Choose "C++ file (.cpp)", enter the name of the file
(as enginedemo.cpp) as you wish. Click OK.
Copy the code from the source file: engwindemo.c, and paste it into this
file enginedemo.cpp. The file engwindemo.c may be obtained from the following
location:
$MATLABROOT/extern/examples/eng_mat
where $MATLABROOT is the MATLAB root directory, and may be determined by
entering the command:
matlabroot
at the MATLAB command prompt.
I'd suggest that at this point you open it in Notepad and if it has some
weird format, fix and save it so it looks like a normal C file when you open
it in Notepad (or gedit or whatever).
This is where things change in Visual Studio and I hope this extends somewhat
transparently to VS Code, Eclipse, or whatever IDE you'd like to use.
So I will re-number the property change section in roman numerals and fix the
order.
Also be sure to hit ENTER and then APPLY after making every change.
Make sure of the change before you go to the next section.
Double-check the spelling and MAKE SURE the directories exist on your
platform.
Go into the Solution Explorer view, Right click on the project name and
select PROPERTIES in the solution explorer to open the project properties.
Once this window has opened, make the following changes:
Go to the Configurations bar at the top of the property page.
You most definitely want to start with this setting.
Pick a configuration, debug or release, or "all configs" if you want the
changes to apply to BOTH debug and release, or you will have to do them all
over again for the other configuration. Which may not be such a bad idea, as
the individual release options are often more "optimized" versions of the
corresponding debug options. Note you can run
into serious trouble changing the property values while switching between
debug and release modes, don't be surprised if the IDE crashes, the solution
database gets corrupt, even the debug won't build and you have
to start all over. Get the debug to work first, back-up the entire solution,
then "clone" the debug settings to release, and then tweak the release
settings one at a time, making sure that the code still builds and runs
between each change.
If compiling to 64-bit Windows, change the target from x86 to x64 & use 64-
bit DLLs and library files.
If this is not in the Configuration options at the very top where it says
"Configuration Manager" (as in VS2015), then follow your IDE instructions...
as mentioned on the following link:
https://www.microsoft.com/en-us/download/details.aspx?id=55984
Under
Configuration Properties ->Debugging
Add the following Target path in the Environment:
(for 32 bit MATLAB)
PATH=$matlabroot\bin\win32
(for 64-bit MATLAB)
PATH=$matlabroot\bin\win64 If you want to use an absolute path instead,
use the following (with a semicolon at the end)
PATH=C:\Program Files\MATLAB\R2013a\bin\win32; (for 32 bit MATLAB)
PATH=C:\Program Files\MATLAB\R2013a\bin\win64; (for 64 bit MATLAB)
(probably can skip the "PATH=" here as it doesn't seem to remain there,
otherwise this is straight from the MATLAB reference )
Under C/C++ General, add the following directory to the field ADDITIONAL
INCLUDE DIRECTORIES:
$MATLABROOT\extern\include
i.e.
c:\Program Files\MATLAB\R2019a\extern\include;
Put a semicolon at the end of every line that you enter that is a path. after
the .lib files in that section also.
Under C/C++ Precompiled Headers, select "Not Using Precompiled Headers".
(in release mode this was set to "yes")
Under Linker General, add the library directory to the field ADDITIONAL
LIBRARY DIRECTORIES:
(For 32-bit Windows)
$MATLABROOT\extern\lib\win32\microsoft
(For 64-bit Windows)
$MATLABROOT\extern\lib\win64\microsoft
i.e.
c:\Program Files\MATLAB\Rxxxxx\extern\lib\win(32|64)\microsoft;
Under Linker Input, add the following library names to the field marked
ADDITIONAL DEPENDENCIES:
(use this string in front of whatever else is in there)
libeng.lib;libmat.lib;libmx.lib;
I don't know if the order really matters, but the original reference listed
them in reverse alphabetical order. "I've heard it both ways".
Ok, now you're done changing the VS project property pages, save the changes
(as you've done all along by clicking "Apply" after each change) and click
Ok. The property pages window will close. At this point your code will build
but still won't call Matlab. Back-up the solution again.
Now change the DOS/WINDOWS ENVIRONMENT PATH STRING.
I would save the solution, close VS, back it up, make the PATH changes and
reopen VS and try to build your program and run it and have it work.
The PATH string must be changed so that the bin\win(32:64) directory is the
first instance related to Matlab on the path.
Go in the "advanced system settings" \ Environment
To do this, check the Windows system path by clicking on Start -> Right click
on Computer -> Properties -> Advanced System Settings -> Environment
variables -> System Variables -> Open "Path" for editing.
and modify the PATH variable as so:
Make sure that the following directory is in the PATH:
(For 32-bit Windows)
$MATLABROOT\bin\win32
(For 64-bit Windows)
$MATLABROOT\bin\win64
It does not have to be the first directory in the path, but it needs to be
the first MATLAB directory in the path
PATH=c:\;....;c:\Program Files\MATLAB\Rxxxxx\bin\win(32/64);
The matlab.exe is in \bin; you might want that on the path also just not
before the \bin\win64 entry...
Note: If the machine has more than one MATLAB installed, the directory for
the target platform must be ahead of any other MATLAB directory (for
instance, when compiling a 64-bit application, the directory in the MATLAB
64-bit installation must be the first one on the PATH).
Also make sure that your target install of
MATLAB is registered as a COM server:
https://www.mathworks.com/help/matlab/ref/regmatlabserver.html
For Matlab 2020a & later, try comserver('query') and comserver('register').
For 2019 & earlier use regmatlabserver() (run Matlab as administrator).
Build and execute the application.
So I include a simple app that should demonstrate the functionality:
#include "stdafx.h"
#include "engine.h"
#include
using namespace std;
int main()
{
Engine *eng;
eng=engOpen(""); // put a breakpoint here
cout << "...now you see it...\n"
engClose(eng); // put a breakpoint here
cout << "...now you don't!\n"
return 0;
}

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.

c1010070: Failed to load and parse the manifest

I have an existing wxWidgets project which I am trying to compile under Visual Studio 2010 (the project was created probably with older version of Visual Studio - could be even VS2003). I compiled wxWidgets library (also included paths in my project). When compiling my project now, I get this error:
1>------ Build started: Project: Terminals, Configuration: Debug Win32 ------
1>Build started 8/24/2015 10:56:23 AM.
1>InitializeBuildStatus:
1> Touching "Debug\Terminals.unsuccessfulbuild".
1>ClCompile:
1> All outputs are up-to-date.
1>ResourceCompile:
1> All outputs are up-to-date.
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>Link:
1> All outputs are up-to-date.
1>Manifest:
1>
1>wx\msw\wx.manifest : general error c1010070: Failed to load and parse the manifest. The system cannot find the path specified.
1>
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:01.59
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Can someone help?
This happens if your project's path has a space in it, for example in my case the project is within my Windows account, so the path begins with "C:\Users\Adam Reece...". I then get "C:\Users\Adam" within a "cannot find" like error when building the manifest.
This is 100% a bug with Visual Studio recently of which Microsoft refuses to recognise. You are not in the wrong for having a space in your path as it's been supported since Windows 95. However as a workaround you either need to make sure there are no spaces in the full path to your project, or disable generation of the manifest. (Project properties -> Linker -> Manifest File -> Generate Manifest -> Change to No (/MANIFEST:NO).)
Based on your description, I suggest you to validate your manifest file and make sure it is correct. You can use Manifestchk.vbs or “ mt.exe -manifest 1.manifest -validate_manifest “.
Moreover, from your error message, you need make sure the complier can find your manifest file configure your configuration correctly.
Go to “Configuration Properties -> Linker -> Manifest File”; turn the
“Generate Manifest” to “No”.
Go to “Configuration Properties -> Manifest Tool “; add your manifest
file path, like: (give mainfest file name like “f:/xxxx.manifest”) to
“Additional Manifest Files”; and turn the “Embed Manifest” to “No”.
Eventually, rebuild again.
If you have any more questions, please feel free to let me know.
This error message always happen when Visual Studio could not find the file. There are some potential causes:
Numbers or spaces in the project name
Project name too long
Started creating the project from a blank project that doesn't have
all of the parts.
I'd suggest trying each of the following to see if it fixes the issue- but backup your project/solution directory first.
A) Clean and rebuild the solution
B) Right click on the solution for the project (in Solution Explorer) and rename the solution to a very simple name (e.g., soln). Then do the same for the project (e.g., rename to proj). Do a rebuild all and see if the problem goes away. If it does you can rename the solution and project to something more meaningful.
C) Right click on the project and open it's properties. Go To Link | Manifest and turn off use of the manifest. Rebuild.
D) Create a new Win32 console project. Have Visual Studio create the initial CPP and .H files you need. Open your old source files and copy the code from those into the new files. Rebuild the new project.
I had the same problem and found the solution that DOES NOT require creating a new user profile...
Yes, it is caused by spaces in usernames. But why? Because mt.exe uses TEMP/TMP environment variables. On one of my machines, the username was with the old 8.3 format in TEMP (C:\users\gerson~1) and that worked. This gave me a hint as to how to adress the problem:
set your users' TEMP to some folder that has no spaces
set your users' TMP to some folder that has no spaces
Ensure you restart VS so that the settings changes take effect. Your build should work now ;)
I had this error together with msb3073. I solved the issue by modifying the project's vcxproj file, changing from:
<PostBuildEvent>
<Command>mt.exe -manifest DesignedForWindows7.manifest -i [...]
</Command>
</PostBuildEvent>
to
<AfterBuildEvent>
<Command>mt.exe -manifest DesignedForWindows7.manifest -i [...]
</Command>
</AfterBuildEvent>
where, in place of [...], there is some command line code that I just copied-pasted.
Be careful that there might be more than one such code block in the vcxproj file
UPDATE 02/07/21: Found a solution for Win10.0..... SDK
https://stackoverflow.com/a/49276285/16360714
I got c1010070: Failed to load and parse the manifest
because my Windows User Profile had a space in it e.g. C:\Users\ John Doe\ and I was trying to use UE4 with C++ and Visual Studio 2017, Win 8.1 SDK
FINAL SOLUTION AT END
Solution 0: CHange TMP and TEMP Windows environment variables to folders with no space. This could break other programs. I kept it changed though while trying other solutions.
Solution 1: Exclude C\User\John Doe ... folders from the project
Solution 2: Try to change your Windows Profile Folder Name (tutorials on YouTube)
Solution 3: Create a new Windows local account with no whitespace and use it for dev
Solution 1 Explanation
If you are using UE4, Makefile will be your Project Configuration default. So you won't have access to Linker or Manifest Tool Settings.
I was getting the following errors when building:
Severity Code Description Project File Line Suppression State
Error c1010070 Failed to load and parse the manifest. The system cannot find the file specified. VirtuPilotv3 C:\Users\John
Severity Code Description Project File Line Suppression State
Error LNK1327 failure during running mt.exe VirtuPilotv3 K:\VRDEVELOPMENT\Virtu-Pilot\Intermediate\ProjectFiles\LINK 1
1
Severity Code Description Project File Line Suppression State
Error MSB3073 The command "K:\VRDEVELOPMENT\UE_4.26\Engine\Build\BatchFiles\Build.bat VirtuPilotv3Editor Win64 Development -Project="K:\VRDEVELOPMENT\Virtu-Pilot\VirtuPilotv3.uproject" -WaitMutex -FromMsBuild" exited with code 6. VirtuPilotv3 C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.MakeFile.Targets 44
I noticed the Macro $(PATH) in Property Page>General>Executable Directories contained a C:\ Users folder path "C:\Users\John Doe.dotnet\tools" to be specific.
So I added the .dotnet folder to my exclude directories and BINGO! I could build and open the editor. [1 VISUAL STUDIO WARNING]
Discovered C:\Users\John Doe.dotnet\tools is found under Windows "path"Environment Path Variables Image variable
I'll probably make a copy of the .dotnet folder to something like C:\VisualStudioCustom and add that folder as Windows Path New .dotnet folder set as path. This Should Solve the problem for all projects. As the new folder will automatically get added to Visual Studios Macro $(PATH). [IT ACTUALLY WORKED, NO VS ERRORS]

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.

Pass file as an argument to visual studio

I try to debug a program in VS2010. In Windows PowerShell I type./Nbody.exe ./config.txt. But, when I enter .\config.txt or other forms of it in the Command Argument form Debugging section from Property Manager window it seems that my program cannot find the file. In fact this part of my code respond:
ifstream CSVfile(CSVFileName);
if (CSVfile == NULL) {
cout << "ERROR: Cannot Open CSV file" << endl;
exit(1);
}
Visual studio calcutates relative paths starting at working dir path. So, you have to use visual studio variables as $(ProjectDir) to compound the paths of your files.
Something like: $(ProjectDir)\config.txt, otherwise you have to set the path relative to working dir path.
Let's say your structure is this:
project_name
+ project_name
| project_name.sln
| debug
| project_name.exe
| config.txt
+ ipch
and you have .\project_name\project_name as working directory.
The path you enter in the project configuration for debugging has to be relative to the working dir:
..\debug\config.txt
Update
As #Goku states in his (I'm assuming Goku is a 'he', :) ) comment:
For VS2017, $(ProjectDir) already contained a '\' concatenated on the directory name.