I am new to c++ and am making a very simple program. All my program does is call a function from the main function, which reads in a text file and returns. To check that I am reading in the file correctly, I am trying to print out the strings I have read in. The print out (cout) works properly when I run from Visual Studio (f5). However, when I run the executable from command line, none of the print outs from my function show up. Only print outs directly in the main function appear. I cannot find a similar question elsewhere. Any help would be appreciated.
When you run a program from within VC++ the current directory is set to the project directory by default, but the application is by default in a different folder.
E.g. the application may be:
D:\Work\MyApp\Debug\MyApp.exe
But the project directory may be:
D:\Work\MyApp\MyApp\
When you start the program from outside of VC++ you need to take steps to make sure the current directory is correct, or that the executable and any data files it refers to are in the same folder.
The default working directory for an IDE-launched project in Visual Studio is the project folder. This is the folder where you project file resides (the .vcproj or .vcprojx file is the project file).
If the data file you are reading is in the same folder, code like this:
std::ifstream inf("datafile.txt");
will succeed because the current working folder and the folder where the data file resides are the same.
However, if you switch to where the executable was written (typically this is the project-dir/Debug or project-dir/Release folders) and run the same executable from a command-shell, the data file will not be found.
To test this is the case. Do the following:
Open a command prompt.
Switch to the project folder where your data file resides.
Run the executable with a specified path: ./Debug/YourProgram.exe, for example.
Note: you can avoid this by having the program take the data file name as an argv[] parameter. Then your program will simply use whatever file you tell it to at launch-time.
Related
I'm trying to run a single program that opens a image file in Clion C++:
See image:
As you can see here, i have a file named "Reso" and a image named "test.png", but this code always will promt "Error reading image"
NOTE: I have proven that this does work in Visual Studio perfectly, but for some reason the file is not recognized in Clion
When you run a binary in CLion, your application will have by default the current working directory set to where your binary is located, which is probably somewhere in your cmake-build-debug directory.
In your case you expect a certain directory, because your resource file is somehwere else. You can either change your code to allow passing the path by argument, or you can set the working directory in CLion for your binary.
In the top you have this bar, where you can choose your build target. There is an option Edit configurations and when you open this and select your target, you can see a field Working directory. Set this field appropriate for your project.
I have made a simple scoring system which upon correct answer, stores the numbers of the player in the file.
I have used the file name like this :
ofstream outfile ("C:\Aadam\Desktop\Project\Scores.txt",ios::app);
But the problem with this approach is that what if I move the program over to a USB and try to run it in another computer. Now it will look in the directory I specified above but there is no Scores.txt file in there.
What I want to do is to give it a path which is in the project folder. So when I move the program, it shouldn't make a difference because I will move the whole project folder.
Of course I can do this :
ofstream outfile ("Scores.txt",ios::app)
which will always look in the project directory and it will work fine as long as I run the program from the IDE but what if I run the program from the .exe file which is two directories down like
"C:\Aadam\Desktop\Project\bin\Debug\Project.exe"
Now in this case, it can't open the file.
So if you know a good way to open files and kindly, Show me the Way.....
You can parse argv[0] (it will contain path used to invoke your executable - absolute or relative) and replace executable name in it with "Scores.txt"
The easiest way is to pass the file path to program as an argument.
When you run a program from IDE, the project directory is considered as current working directory. If the program is run from the command line, the current working directory is from where the command is being run.
If you run the exe file,ofstream outfile ("Scores.txt",ios::app) will create a file named "Scores.txt" in the same directory as your program.
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.
When I run the Debug in Visual Studio for a project, fopen function works fine. It tries to open a file contained in the project and that I added in the filter "Resources".
But when I run .EXE file of my project, I get the null pointer exception: 0x000005c.
When I added the file to be in the same directory as my .EXE file, the exception disappeared.
This is the instruction I use :
fopen(&filename, "rb");
I know it is adviced to use fopen_s instead, but the file is not found anyway...
Apparently, the file is searched always in the current directory...
So, how to include the file in .EXE and make the path of the file relative to the .EXE, at a way it will be contained in the .EXE and not added to the directory where there is .EXE?
You can't include the file in the .exe. You just need to make sure that the file is in the same directory as the .exe.
If you really, really want to only use one file, you could either:
Zip the .exe and the text file together and make sure you include in a readme that the text file needs to be in the same location as the .exe
Use an array/struct/some other way of storing the contents of the file in the program itself, and reference that instead of using a file (I assume you don't care about users being able to edit this data outside of an instance of the program since you wanted it bundled with an executable, so the file is unnecessary in that case)
The reason the program only works when you put the file in the directory of the .exe is because the path to the file is defined in the program as something like .\file.txt or file.txt. When the file isn't in the same directory as the .exe, the program will try to find it, and will be unable to, which is why you get the error. It works when you debug because you have a copy of the text file in the same location as the debug .exe.
EDIT: I would also ignore the warnings about fopen_s and other variant's that append a _s to the end of a command - these are windows specific, non-standard, and in most cases, pointless. If you know this program will only be used in windows environments and you're not doing something for school where you are required to write standard code, I suggest you use the _s variants for the sake of security, but it will reduce portability of your code.
I am having a bit of trouble running my C++ program as a .exe file. It takes in one input file (specified in project properties > debugger: < input.txt) and outputs two files.
When I run the program within Visual Studio itself, everything completes just fine. The files being written are correct. However, when I try to run the .exe file, it does not seem to do anything.
Project name = test
I am running the .exe from: test\Debug\test.exe. That's the only location within the VS project folder that I see an .exe file. I have also moved the expected input.txt to this same location. Can anyone help me troubleshoot?
It sounds like you are passing input.txt as an argument to the program. In this case you have to start the program like this:
test.exe < input.txt
That's what VS does for you when you debug the program. Putting the file next to the program is not the same as passing an argument.