input file from command line - c++

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).

Related

How to take characters in a text file as arguments

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;
}

Why does reading a file that doesn't exist print garbage characters?

I try to understand the file reading in c++ and try to read a file that doesn't exist deliberately
//includes ommited
int main(int argc, char ** argv)
{
if(argc != 1)
throw std::exception();
std::ifstream file(argv[0]);
std::string content((std::istream_iterator<char>(file)), std::istream_iterator<char>());
std::cout << content.c_str() << std::endl;
}
DEMO
It prints the following:
ELF
Why is it supposed to mean? Do I just get UB by doing this? Since I'm a Java coder I expected that some exception will be thrown if we try to read a file that doesn't exist...
argv[0] contains path to your executable.
http://www.gnu.org/software/libc/manual/html_node/Program-Arguments.html
The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.
Just try to print it's contents:
std::cout << argv[0] << std::endl;
You probably want to use argv[1].
"ELF" is the begin of file header of Executable and Linkable Format.

Error when trying to open multiple files in c ++

I'm trying to open multiple files to compile the data in them. My program compiles but when I run it i get the following error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
So far my program is pretty lengthy so I'll just link the parts of it that deal with opening the files.
int main(int argc,char *argv[])
{
vector<Plays> yearsEntered;
Plays *MyPlays = new Plays();
if (argc < 2)
{
cout << "No filenames given." << endl;
return 0;
}
for(int i=1;i < argc; ++i)
{
string filename = argv[i];
cout << filename << endl;
filename.append(".csv");
cout << filename << endl;
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
//Error checking in case file fails to open
if (!inputFile)
{
cout << "Could not open file. " <<
"Try entering another file." << endl;
}
}
I'm not quite sure why I'm getting an error but if I had to guess i'd say it was something to do with the fact that argv[i] is a *char array and I'm setting it equal to a string. Also when i run the program it's run like this: ./Analyze 2009 2010 (etc). When i run it it'll print out the name of the file that I want to open so I know the problem is when it tries to open the file itself. This is my first time asking a question so if there's any convention I failed to follow let me know and I'll try to fix it.
You already opened your files once. You don't need to open them again.
The std::ifstream constructor is opening each file, then your invoking .open() for no reason. Remove the inputFile.open() line.
Change this:
ifstream inputFile(filename.c_str(), ios::in);
inputFile.open(filename.c_str());
To this:
ifstream inputFile(filename.c_str());

File cannot be read in when using Visual Studio 2010 Debugger

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.

Windows drag and drop problem with console app

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