I am new to using the command line to start up a program. I want to call my file, called "file.txt". I've been searching for examples but I have not seen what the command line writes.
int main(int argc, char *argv[])
{
if (argc < 2) {
cerr << "Error: file name argument not given" << endl;
exit(1);
}
ifstream inFile( argv[1], ios::in);
}
Got it. So through the command line I navigate to my .exe and call the file I want after.
C:\Users\me\sampleProject\bin\Debug>test.exe sampleFile.txt
And it works.
Thanks.
Related
I'm fairly new to C++, I'm trying to figure out how to take in arguments from a text file and use them in my program.
So if I wanted to include a text file whatever.txt in a command, it would use specified lines as arguments.
Like if the text file looked like this:
1 2
and I wanted to use 1 and 2 from it, as arguments in my program.
So far from what I've gathered, I need something akin to this:
int main (int argc, char const *argv[]) {
to start, but not sure where to go from here.
I'm trying to mess around with certain stuff, but I'm still pretty new and outside of loops and things I can't do much with the language yet!
Short of giving you the code that will do this for you (which would ruin the fun of learning how to do these things), the steps I would follow would be:
Take one argument from the command line as the file name you want to read the information from. Think of running your script like this:
$ ./myscript whatever.txt
Then, argv[0]="./myscript" and argv[1]="whatever.txt".
Open the file (perhaps ifstream would be good for this).
Loop through each line of the file (maybe using getline to put each line into a string)
Parse each line of the file (I've seen stringstream used for filling variables from a string).
Hopefully that will help you along your way.
int main(int argc, char *argv[])
after retrieving files names in the main function you should open each file and retrieve its contents
Sample code
int main(int argc, char* argv[])
{
for(int i=1; i <= argc; i++) // i=1, assuming files arguments are right after the executable
{
string fn = argv[i]; //filename
cout << fn;
fstream f;
f.open(fn);
//your logic here
f.close();
}
return 0;
}
https://stackoverflow.com/a/30141375/3323444
argc is the number of arguments passed in to your program, argv is an array of character strings holding the names of arguments passed in.
at least there's one parameter passed in which is argv[0] which is name of program.
after building this code run it form a command prompt as:
main.exe data.txt
or simply DRAG AND DROP file "data.txt" on your main.exe
main.exe is your program, data.txt is text file containing data you want to use
#include<iostream>
#include<fstream>
int main(int argc, char* argv[])
{
char c;
if(argc < 2)
{
std::cout << "No file passed to program!" << std::endl;
return 1;
}
std::ifstream in (argv[1] , std::ios::in);
if(!in)
std::cout << "Unable to read file: " << argv[1] << std::endl;
while(in >> c)
std::cout << c << std::endl;
in.close();
std::cin.get();
std::cout << std::endl;
return 0;
}
I want to get the input file name in advance, when my program is called, not have my program ask the user for the filename.
I've seen many examples where the program will ask the user for input like:
int main()
{
cout << "Enter file name: ";
cin.get();
//run program
return 0;
}
However, there are not many examples shown where the input is stated in the command line when the program is called:
int main(int argv, char* argc[])
{
ifstream inputfile;
inputfile.open(argc);
//run program
return 0;
}
In other words, the user would type something like this on the terminal:
$./program example.txt
Sorry if my question is like an ELI5 submission.
I think you guys might get the gist of what I am trying to do.
Use:
int main(int argc, char* argv[])
{
ifstream inputfile;
if(argc == 2)
inputfile.open(argv[1]);
else
cout<<"Please nenter filename as command line argument!\n";
//run program
return 0;
}
Here, argc and argv are called command line arguments.
The value of argc is equal to the number of command line arguments, which includes the filename of the executable file itself.
argv is an array of strings passed as command line arguments, where the name of the executable file is at argv[0] and the rest of the arguments follow that.
You need to use:
inputfile.open(argv[1]);
However, I suggest adding checks to the program.
int main(int argc, char* argv[]){
if ( argc < 2 )
{
cerr << "Not enough arguments.\n";
return EXIT_FAILURE;
}
// There is an argument. Use it.
ifstream inputfile;
inputfile.open(argv[1]);
//run program
return 0;
}
I'm here to trying to take input from the file. If user run this .exe from cmd and give a filename like example.exe input.txt
then it shows the file and read. But if user doesn't give the file name then it run as simply program's run.
Program is running well when I give the input from cmd during run time it run perfectly, but if I don't give the filename during running this file and run simply example.exe an exception show me the error
exception: invalid null pointer
my code is here:
// inputfile.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>
using namespace std;
void main(int argc, char* argv[])
{
try {
if (argc > 0)
{
string filename = argv[1];
ifstream in(filename);
in.open(filename);
if (in.is_open())
{
cout << "file opened, do something with file";
}
else
{
cout << endl << "You have Entered Wrong File Name Or File Not Exist in Project's Library" << endl;
}
}
}
catch (exception e)
{
}
cout << endl << "do with the simple program";
_getch();
}
The logic error is in the line
if (argc > 0)
It needs to be
if (argc > 1)
argv[1] is NULL if the program is invoked without arguments.
argc is at least 1, the first argument being the name of the program. When the program is invoked with one argument, argc is 2 and argv[1] is the first argument.
When there is only one argument(always the exec file itself, e.g. using in the way ./exec_file or just double click the exec file), the argv[1] would throw an exception.
Here are some tips:
Try to learn how to debug the code(IDE like Visual Studio, Ecplise or gdb).
VC++ is not standard c++, which means it only runs on Windows, not cross-platform. You'd better learn to use g++ compiler(linux).
So, I am using https://stackoverflow.com/a/298713/1472828 to put an argument "hands.txt" (my agrv[1], which is a file I wanna open) in my command arguments. I have tried both hands.txt and "hands.txt", neither of them worked.
int FileParsing(vector<Card> & v, char * FileName) {
ifstream ifs;
ifs.open(FileName);
if (!ifs.is_open()){
cout << "file cannot be opened." << endl;
} else {
So I use debugger to step through my main:
int main(int argc, char * argv[]){
if (argc !=2 ){
//ErrorMessage();
} else {
...
Debugger tells me that my argc is 2, which is right, but how come every time the debugger just goes to
cout << "file cannot be opened." << endl;
which means the argument just fails at reading it
ifstream ifs;
ifs.open(FileName);
Is there something I missed or I passed the argument in a wrong way?
p.s. The text file was read perfectly from cmd, so it's not the problem of code.
Got the idea from #WhozCraig, while running your program in cmd, the text file is put under debug directory. But if you run it using debugger, you have to put the text file in the same directory with other cpp and h files.
I have a program that creates a file and writes to it using ofstream. I need the program to be able to parse command line parameters later on. But for some reason, it does not create a file when I drag-and-drop a file onto the compiled executable, even if the program doesn't involve any command line parameters at all. If the executable is run normally, it works. So I'm left totally confused. Here is the source:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outfile;
outfile.open("test.txt");
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Does anybody have any ideas? I appreciate any help.
You are not using the command line arguments at all. Recode your main() method to look like this:
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Usage: blah.exe file" << endl;
return 1;
}
ofstream outfile;
outfile.open(argv[1]);
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Be careful what you drop, your code rewrites the file contents.
The following code does what the OP wants:
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char ** argv )
{
cout << argv[1] << endl;
ofstream outfile;
outfile.open("testzzzzzzz.txt");
if(outfile.is_open())
{
outfile << "Testzzzzz";
outfile.close();
cout << "wrote file"<< endl;
}
else cout << "Unable to open file";
string s;
getline( cin, s );
return 0;
}
It allows drag and drop, but doesn't use the dropped file name in the file open. When you drop a file in it, you get the message
"wrote file"
Unfortunately, at the moment I have no idea where it wrote the file - not in the current directory, definitely. Just going to do a search...
Edit: It creates it in your Documents and Settings directory. So to put it in the current directory, you probably need to explicitly prefix it with "./", but I havent't tested this - I leave it as an exercise for the reader :-)
Since you have not specified a path, the file, test.txt, will be saved to the default path. Just bring up a command prompt (i.e. run cmd.exe) and the command prompt will show you the default path. The file should be in this directory.
You can change the default path by editing the HOMEDRIVE & HOMEPATH environment variables.
Also, you should note the other answers. You should be using argc/argv to specify the output file.
you haven't specified a path for "test.txt" so it will try and create that file in the current working directory of the executable. This will be different when the exe is invoked by dropping a file on it than it is when you run the program normally.
Try giving "test.txt" a full path and see if that works.
edit:
To write your output file to the path that contains the exe, you would use
GetModuleFileName(NULL, ...) to the the full path of the exe,
then PathRemoveFileSpec to strip off the exe name, leaving just the exe path then
PathCombine to append test.txt to the exe path