File as Command Line arguments - c++

I am new to C++ and I am learning with Visual Studio.
I want to make a small program that reads a text from the command line and opens the text. I know that my program has to start like this:
int main (int argc, char *argv[] ){
ifstream File( argv[1] )
But I am super confused on how to run it from the Visual Studio Command Prompt. I know there are a lot of questions like this but I still haven't found what I am looking for. I read that you have to go to properties, Debug and change the command line arguments, but what exactly do I need to put in there? And what should I type in the VS Command Prompt.
Thank you!

From menu find: Project->Properties. Or from the Solution Explorer tree right click on the project and select Properties.
Now, in the opened dialog left pane select: Configuration Properties->Debugging
Then in the right pane grid find the line titled: Command Arguments
Fill it with the input file name (I think you better put it there as a full path, if there is a space in the path use with double quotas. like this:
Without space:
filepathwithoutspace.txt
or with spaces:
"file path with spaces.txt"
Good luck.

For starters, your code should not start like that: before
passing argv[1] to std::ifstream::ifstream, you should
verify that there is an argument, and output an error message
otherwise. As it is, you could end up passing a null pointer to
the constructor of ifstream, which will result (normally) in
a program crash.
As to how to run it: where did you put the executable? If
you're in the Visual Studio Command Prompt window, and have
invoked cl, then by default, the executable should be in the
local directory. Just enter .\name, where name is the name
of your program. If you've actually compiled it from within the
IDE, then in the command window, you should use cd to navigate
to where the executable was generated (which you can find out
from your properties), and invoke it as above; or you can simply
specify the path completely:
c:\Users\me\whereeverIPutTheThing\name.
If you want to debug (using the debugger), you need to specify:
1) the name of the executable (but the default should be good),
2) the parameters to pass it (what you want to see in
argv[1]—don't forget the quotes if it has a space in
it), and 3) the directory where the executable should run. The
second and third are somewhat interdependant: you can, for
example, specify just the filename in 2, and the path where the
file is located in 3, or you can specify the complete path to
the filename in 2, and forget about 3. Or use a combination of
the two: in practice, I tend to do everything from the root
directory of the project, so I'd specify a path relative to this
directory, and then the path from my project file to this root
in 3. (The way we have things set up, this is ..\..\.., but
I think you'll find it somewhat shorter.)

Related

g++ is not recognized as an internal or external command Windows 10

First off I would like to say I've seen the previous questions on this site, I've tried every solution but none fit my use case or solves my problem.
I am having trouble with the g++ complier being recognized, I've included this path:
C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
which is where the current version of mingw is located (recently downloaded). I've also tried other options like changing the path to gcc.exe, and just regular bin. Someone please provide a detailed solution to this problem.
Other things i have tried and looked at closely would be:
http://stephencoakley.com/2015/01/21/guide-setting-up-a-simple-c-development-environment-on-windows
seeing as though I'm working through sublime text 3
Another thing Ive tried:
Ive tried to copy and paste the path into cmd and run it , but i find this error code:
C:\Users\Kxrk>C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.
So seeing that, i tried another way , and that is to drag the file and drop it into cmd and get this :
C:\Users\Kxrk>C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe
g++.exe: fatal error no input files
compilation terminated
when u drag and drop the file it has double quotes around it , so i tried editing the path to contain double quotes around it and the path automaticlly changes back after saving.
This was very simple , it was one of those weird cases.
To solve my problem what i did was:
1: uninstall , the current version of the mingw compiler , because i felt as though the one i had was corrupt in a way.
2:Redownloaded it the compiler from the website http://www.mingw.org/
3: set up the new Environmental variable where i save it , witch was C:\MinGW\bin
I had to install g++ from the command line(cmd ,command prompt)
by using this command mingw-get install g++witch is located inside bin on default
now i created one more directory in the environmental variables , C:\MinGW\bin\g++.exe
6.Now everything works , and is normal
If you are trying to run the compiler from the command line then you have to put double quotes around the path, because the path contains two whitespaces (this is the reason for the first error).
The reason for second error is that you didn't specify which C++ program you want to compile. You have to append the filename of your C++ input file to your command:
C:\Users\Kxrk>"C:\Program Files (x86)\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32\bin\g++.exe" program.cpp
See Barmak Shemiranis answer if don't want to enter the full path all the time. After that you can just use this:
C:\Users\Kxrk>g++ program.cpp
You have to use quotation marks around the path so that is treated as a single path:
c:\>"c:\program files\path\g++.exe"
A better way is to set the environment variables. Open Environment variables windows (in Windows 10 you can type in "environment variables" in search box) or right click on "Computer" in desktop, open "Advanced System Settings" and find the button for "Environment variables"
Go to your command propmpt, type set path, it will show list of directories, copy them,
Now type set path=<data you copied> and then add a semicolon and possible directory to g++ usually C:\MinGW\bin

CLion standard input while debugging

What I'm trying to do is basically:
./myProgram < myData.txt
While I'm debugging with CLion IDE. I just can't find the option to do so.
A similar question - but product-specific to MSVS
I had the same problem and it seems that CLion is not handling standard inputs yet.
I got around this problem by changing the input stream before running my program.
As an example if you want to input a file stream inside your stdin you can write in your main:
std::ifstream in("ABSOLUTE_PATH_TO_YOUR_FILE");
std::cin.rdbuf(in.rdbuf());
Then you can find a way to toggle this stream change when you want. Note that for files you will need to provide absolute path since the application is run from a different directory than the current one.
I hope this can help until CLion provides a real solution.
Assuming your input file is myData.txt, you can reopen/reuse the stdin stream using freopen
freopen("myData.txt","r",stdin);
if you want to do the same with your output:
freopen("myOutput.txt","w",stdout);
this will work for std::cin, printf, etc...
You can find more information about this here: http://www.cplusplus.com/reference/cstdio/freopen/
By the way, there is already a feature request for this. If you are interested, you can vote here so it gets prioritized:
https://youtrack.jetbrains.com/issue/CPP-3153
As of CLion 2020.1 this feature is built in:
Input redirection
If you need to redirect input from a file to the
stdin of your application, you can now do that. Use a new field in the
configuration called Redirect input from. Enter:
A relative path (CLion will prepend with the Working directory path).
An absolute path (will be remapped for remote configurations).
Or macros (like FilePrompt).
Still Clion don't have the feature like pycharm where we can give input in terminal while debugging the code.
But it has an option to give input through a .txt file while debugging.
Image of debug setting window
Click the setting icon in the debug console (on upper left corner) to open the setting of debugging. Then check the "Redirect input from" box and select the input file path and click "OK".
Here you go!
Now you can give input from the text file while debugging the code.
For me, CLion creates the executable in a file called 'cmake-build-debug'. Check out my file structure in the pic.
Then, I just opened up my terminal and went to the directory containing the executable and used this command to pipe in the text file:
./FirstProject < ../hw1.txt

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.

Qt: QProcess result doesn't match result at prompt

I'm trying to execute the following command from Qt:
explorer /select,C:\Temp Folder\temp.wav
This should show the file temp.wav as selected in an Explorer window. It works correctly when run from the command prompt.
However, when I try the following in Qt:
QProcess::startDetached(
"explorer",
QStringList("/select,C:\\Temp Folder\\temp.wav")
);
it doesn't work -- it opens Explorer but puts me in the "My Documents" folder. If I rename the folder to one without a space (TempFolder), it works correctly.
I've tried escaping the space in the folder name, placing quotes around the entire path, and many other combinations without success. Many combinations work correctly in cmd but do not seem to work when called through QProcess::startDetached.
The most confusing part is that the code I'm trying to copy is from QtCreator source code where they use something similar to open up a file in the Explorer window. Theirs successfully opens files with spaces in the path, but I just can't seem to recreate it!
When you make such call:
QProcess::startDetached("explorer",
QStringList("/select,C:\\Program Files\\7-Zip\\7z.exe"));
Qt transforms the argument string into the:
explorer "/select,C:\Program Files\7-Zip\7z.exe"
which is not a valid option to open Explorer and select the given file. This happens, because your single argument has space(s) and Qt escapes it with quotes.
To fix this problem you need to make the following call:
QProcess::startDetached("explorer",
(QStringList() << "/select," << "C:\\Program Files\\7-zip\\7z.exe"));
i.e. pass two arguments. This will produce the following string:
explorer /select, "C:\Program Files\7-Zip\7z.exe"
which is valid and will do what is intended.

How do I open a file in c++ (other than notepad)

I was wondering how to open a file other than notepad... Our prof gave us an example:
s = "notepad.exe test.txt";
system(s.c_str());
That will open a file type of "notepad.exe" and the file name of "test.txt"
Main Question:
Now, I was wondering if there was a way to open other type of files, such as Microsoft Excel, Microsoft Word, Visual Studio, or 7zip.
My attempt opened something in a new cmd.exe (because of the START keyword):
fileNeededtoBeOpened = "START \"New Microsoft Office Excel Worksheet.xlsx\"";
system(fileNeededtoBeOpened.c_str());
(This code is slightly different from my original, where I'm trying to open a file from a vector...) but all I really need to know is instead of "notepad.exe" or "START" is there a different command to open different file types that aren't .txt
Also, a side note, I was reading on the internet that it wasn't safe to use system() to open files, is this correct?
I found the answer by myself... for those who are curious, here an the answers:
To open a text file: system(notepad)
To open an excel file: system(start excel)
To open a word doc file: system(start winword)
To open a 7z file: system(start 7zFM)
To open a visual studio file: system(start devenv)
I think you're confused.
System executes a command as you would on the command line (type cmd into the run prompt under start menu to get that).
So, when you type notepad.exe test.txt it's saying:
Open the program notepad.exe which is on the system path (so the
command line can find it to execute that program), and pass the
parameter test.txt to it.
Notepad itself decides what to do with test.txt, in this case it opens it.
So, you can tell it to run any command (program/executable) and pass any parameters to it in reality. If excel's on your system path, you can probably just type excel.exe to open it from your system command. Otherwise, find the location excel is installed in, and refer to it with the whole path to excel.exe and it will work fine.
For example, on my computer, executing "C:\Program Files\Microsoft Office\Office12\EXCEL.EXE" would open excel from the command line. I can pass further parameters to it by having more information (like filenames) after the Excel.exe" portion, just as you did in your notepad example. Using your system command should have equivilent behavior when that line is executed.
If you are only targeting Windows systems you can use the ShellExecuteEx function (part of the Win32 API). You can just pass a filename to it and it will launch what ever program is registered to handle that file type (just as if you opened the file from windows explorer). Documentation is available on MSDN:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb762154(v=vs.85).aspx
There is some examples on Launching Applications (ShellExecute, ShellExecuteEx, SHELLEXECUTEINFO) MSDN article and lots more elsewhere around the internet.
AS the other guys mentioned , the System function only executes a cmd command, .. notepad.exe is in the system's path by default so it works directly
but for example for me if I want to open a zip file on my desktop , I'd type something like
"C:\Program Files\7-Zip\7zFM.exe" Desktop\zipfile.zip
that's when I'm currently at the my user's directory [by default] , or
"C:\Program Files\7-Zip\7zFM.exe" C:\Users\JiMMaR\Desktop\zipfile.zip
[where JiMMaR is my user name on windows 7]
note that this certain command works only on windows , if you are using another OS this won't work as it is
try doing a
fileNeededtoBeOpened = "\"C:\Program Files\7-Zip\7zFM.exe\" C:\Users\YOUR_USER_NAME\Desktop\zipfile.zip";
and see if that executes or not
edit:
if you cannot escape the space , then try this one
fileNeededtoBeOpened = "C:\Program~1\7-Zip\7zFM.exe C:\Users\YOUR_USER_NAME\Desktop\zipfile.zip";
Ok, firstly - system - is a function that starts a separate process to your program. Much the same as in a command window when you type the command. The command lines you provide will be dependent on the applications you want to launch.
Now, I was wondering if there was a way to open other type of files,
such as Microsoft Excel, Microsoft Word, Visual Studio, or 7zip.
Yes I would be pretty shocked if there wasn't a command line parameter you could specify to load a document in these apps at start up. (Ok not shocked, but it is pretty standard)
Does this have anything to do with c++ - not really - you need to look at references for the applications you mention and see what the command lines parameters are for them. Then craft a string and system(...) to your hearts content.