C++ command line interface help message wont display [duplicate] - c++

This question already has answers here:
How to compare strings
(4 answers)
Closed 1 year ago.
I am trying to make a CLI app in C++. This is my first time coding in C++.
I have this c++ code:
#include <iostream>
// using namespace std;
static void help(std::string argv)
{
std::cerr << "Usage:" << argv << " [options]\n"
<< "Options:\n"
<< "-h (--help): Displays this help message.\n"
<< "-o (--output=[output file]): Specifies the output file.\n"
<< "-p (--ports=[ports]) Sets the ports to scan.\n"
<< std::endl;
}
int main(int argc, char** argv)
{
if (argc > 1)
{
std::cout << argv[1] << "\n";
if (argv[1] == "-h" || argv[1] == "--help")
{
help(argv[0]);
return 0;
}
}
else
{
std::cout << "No arguments were given" << "\n";
};
};
// g++ -o cli main.cpp
It works! When I compile it, it successfully outputs No arguments were given, but when I run cli -h, I can see argv[1] is -h, but nothing is outputted.
What did I do wrong?

In your string comparison, argv[1] is a C string: a null-terminated char array. You cannot compare these with == and get the result you expect. If, however, you assign it to a std::string you can compare it with "-h" and "--help" the way you want.
std::string arg1 = argv[1];
if (arg1 == "-h" || arg1 == "--help") {
help(argv[0]);
return 0;
}
Alternatively you could use std::strcmp to compare C strings without creating a new std::string. In order to do this, you'll need #include <cstring>.
if (std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0) {
help(argv[0]);
return 0;
}

Related

ifstream: /dev/stdin is not working the same as std::cin

For my formation, an exercise ask us to create a program similar to the linux 'cat' command.
So to read the file, i use an ifstream, and everything work fine for regular file.
But not when i try to open /dev/ files like /dev/stdin: the 'enter' is not detected and so, getline really exit only when the fd is being closed (with a CTRL-D).
The problem seems to be around how ifstream or getline handle reading, because with the regular 'read' function from libc, this problem is not to be seen.
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <errno.h>
#ifndef PROGRAM_NAME
# define PROGRAM_NAME "cato9tails"
#endif
int g_exitCode = 0;
void
displayErrno(std::string &file)
{
if (errno)
{
g_exitCode = 1;
std::cerr << PROGRAM_NAME << ": " << file << ": " << strerror(errno) << std::endl;
}
}
void
handleStream(std::string file, std::istream &stream)
{
std::string read;
stream.peek(); /* try to read: will set fail bit if it is a folder. */
if (!stream.good())
displayErrno(file);
while (stream.good())
{
std::getline(stream, read);
std::cout << read;
if (stream.eof())
break;
std::cout << std::endl;
}
}
int
main(int argc, char **argv)
{
if (argc == 1)
handleStream("", std::cin);
else
{
for (int index = 1; index < argc; index++)
{
errno = 0;
std::string file = std::string(argv[index]);
std::ifstream stream(file, std::ifstream::in);
if (stream.is_open())
{
handleStream(file, stream);
stream.close();
}
else
displayErrno(file);
}
}
return (g_exitCode);
}
We can only use method from libcpp.
I have search this problem for a long time, and i only find this post where they seems to have a very similar problem to me:
https://github.com/bigartm/bigartm/pull/258#issuecomment-128131871
But found no really usable solution from them.
I tried to do a very ugly solution but... well...:
bool
isUnixStdFile(std::string file)
{
return (file == "/dev/stdin" || file == "/dev/stdout" || file == "/dev/stderr"
|| file == "/dev/fd/0" || file == "/dev/fd/1" || file == "/dev/fd/2");
}
...
if (isUnixStdFile(file))
handleStream(file, std::cin);
else
{
std::ifstream stream(file, std::ifstream::in);
...
As you can see, a lot of files are missing, this can only be called a temporary solution.
Any help would be appreciated!
The following code worked for me to deal with /dev/fd files or when using shell substitute syntax:
std::ifstream stream(file_name);
std::cout << "Opening file '" << file_name << "'" << std::endl;
if (stream.fail() || !stream.good())
{
std::cout << "Error: Failed to open file '" << file_name << "'" << std::endl;
return false;
}
while (!stream.eof() && stream.good() && stream.peek() != EOF)
{
std::getline(stream, buffer);
std::cout << buffer << std::endl;
}
stream.close();
Basically std::getline() fails when content from the special file is not ready yet.

ERROR: '::main' must return 'int' [duplicate]

This question already has answers here:
What should main() return in C and C++?
(19 answers)
Closed 6 years ago.
This my main function:
void main(int argc, char **argv)
{
if (argc >= 4)
{
ProcessScheduler *processScheduler;
std::cout <<
"Running algorithm: " << argv[2] <<
"\nWith a CSP of: " << argv[3] <<
"\nFilename: " << argv[1] <<
std::endl << std::endl;
if (argc == 4)
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3])
);
}
else
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3]),
atoi(argv[4]),
atoi(argv[5])
);
}
processScheduler -> LoadFile(argv[1]);
processScheduler -> RunProcesses();
GanntChart ganntChart(*processScheduler);
ganntChart.DisplayChart();
ganntChart.DisplayTable();
ganntChart.DisplaySummary();
system("pause");
delete processScheduler;
}
else
{
PrintUsage();
}
}
The error I get when I compile is this:
Application.cpp:41:32: error: '::main' must return 'int'
It's a void function how can I return int and how do I fix it?
Try doing this:
int main(int argc, char **argv)
{
// Code goes here
return 0;
}
The return 0; returns a 0 to the operating system which means that the program executed successfully.
C++ requires main() to be of type int.
Function is declared as int main(..);, so change your void return value to int, and return 0 at the end of the main function.

piping stockfish misbehaves in fedora

Somewhere in my project I use fork and pipe to execute another process and pipe its I/O to communicate with it (I'm writing it in C++). There is no problem when I compile it in Ubuntu 14.04, it will work just fine, but I compiled it in fedora on a WMWare virtual machine and strange things began to happen. If I run the binary in terminal, there is no error but nothing will be written in the pipe (but getting streams of characters will work). I tried to debug my code in fedora, I put a break point in my code, but then a broken pipe signal was given when process tried to read from pipe (there were no signals when executing in terminal).
So, have any of you encountered such problems before? Is there any difference in piping between debian and red hat linux? Or is it because I'm running fedora on a virtual machine?
CODE:
int mFD_p2c [2];
int mFD_c2p [2];
int mEnginePID;
if (pipe(mFD_p2c) != 0 || pipe(mFD_c2p) != 0)
{
cout << "Failed to pipe";
exit(1);
}
mEnginePID = fork();
if (mEnginePID < 0)
{
cout << "Fork failed";
exit(-1);
}
else if (mEnginePID == 0)
{
if (dup2(mFD_p2c[0], 0) != 0 ||
close(mFD_p2c[0]) != 0 ||
close(mFD_p2c[1]) != 0)
{
cout << "Child: failed to set up standard input";
exit(1);
}
if (dup2(mFD_c2p[1], 1) != 1 ||
close(mFD_c2p[1]) != 0 ||
close(mFD_c2p[0]) != 0)
{
cout << "Child: failed to set up standard output";
exit(1);
}
string engine = "stockfish";
execlp(engine.c_str(), (char *) 0);
cout << "Failed to execute " << engine;
exit(1);
}
else
{
close(mFD_p2c[0]);
close(mFD_c2p[1]);
string str = "uci";
int nbytes = str.length();
if (write(mFD_p2c[1], str.c_str(), nbytes) != nbytes)
{
cout << "Parent: short write to child";
exit(1);
}
cout << "The following string has been written to engine:\n"
<< string(1, '\t') << str;
char readBuffer[2];
string output = "";
while (1)
{
int bytes_read = read(mFD_c2p[0], readBuffer, sizeof(char));
if (readBuffer[0] == '\n')
break;
readBuffer[bytes_read] = '\0';
output += readBuffer;
}
cout << "Got: " << output;
}
I see you're using Stockfish. I too have exactly experienced this behavior from Stockfish. The problem lies within how it handles output. Defined in misc.h:
#define sync_cout std::cout << IO_LOCK
And looking at the code again we'll see that IO_LOCK is an enum which is used in an overloaded friend operator for cout:
std::ostream& operator<<(std::ostream& os, SyncCout sc) {
static Mutex m;
if (sc == IO_LOCK)
m.lock();
if (sc == IO_UNLOCK)
m.unlock();
return os;
}
What I see here is that during using cout, a mutex is locked. I don't know how exactly this affects cout's output in a pipe instead of stdout, but I'm positive that this is the cause for the problem. You can check it by removing the lock functionality.
Edit: I forgot to mention that the pipe behavior is not different in linux based systems as mentioned before, but there might be slight differences between distributions handling mutexes used with pipes.
There are no differences in piping between debian and red hat, but the following list of questions may help you:
-Are the Ubuntu and the Fedora using the same architecture (64 bit vs 32) ?
-Are you using the same version of gcc (or any other compiler) ?
(Suggestion: use cerr for your error outputs, and maybe your debug output too -> you dup the standard outputs and inputs, so if something fails you may not see it)
Anyhow, here's how you turn it into a self-contained, compilable example:
stockfish
#cat stockfish
tr a-z A-Z #just so we do something
echo #need to end with a "\n" or else the parent won't break out of the while loop
Run command:
make pipes && PATH=.:$PATH pipes
pipes.cc
//pipes.cc
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
using namespace std;
int mFD_p2c [2];
int mFD_c2p [2];
int mEnginePID;
if (pipe(mFD_p2c) != 0 || pipe(mFD_c2p) != 0)
{
cout << "Failed to pipe";
exit(1);
}
mEnginePID = fork();
if (mEnginePID < 0)
{
cout << "Fork failed";
exit(-1);
}
else if (mEnginePID == 0)
{
if (dup2(mFD_p2c[0], 0) != 0 ||
close(mFD_p2c[0]) != 0 ||
close(mFD_p2c[1]) != 0)
{
cout << "Child: failed to set up standard input";
exit(1);
}
if (dup2(mFD_c2p[1], 1) != 1 ||
close(mFD_c2p[1]) != 0 ||
close(mFD_c2p[0]) != 0)
{
cout << "Child: failed to set up standard output";
exit(1);
}
string engine = "stockfish";
char *const args[]={};
int ret;
execvp(engine.c_str(), args);
//I need the endl here or else it doesn't show for me when the execvp fails; I wasn't able to compile the original exec command so I used a different one from the exec* family
cout << "Failed to execute " << engine << endl;
exit(1);
}
else
{
close(mFD_p2c[0]);
close(mFD_c2p[1]);
string str = "uci";
int nbytes = str.length();
if (write(mFD_p2c[1], str.c_str(), nbytes) != nbytes)
{
cout << "Parent: short write to child";
exit(1);
}
//My particular child process tries to read to the end, so give it the EOF
close(mFD_p2c[1]);
cout << "The following string has been written to engine:\n"
<< string(1, '\t') << str;
char readBuffer[2];
string output = "";
while (1)
{
int bytes_read = read(mFD_c2p[0], readBuffer, sizeof(char));
if (readBuffer[0] == '\n')
break;
readBuffer[bytes_read] = '\0';
output += readBuffer;
}
cout << "Got: " << output;
}
return 0;
}
output:
The following string has been written to engine:
uciGot: UCI

<Unable to read memory> c++

I am trying to run this code in console app in vs 2013 but when I run the code give following error:
-argv[1] 0x00000000 <NULL> char *
<unable to read memory>
this is the main function code:
int main(int argc, char **argv)
{
set_new_handler(memory_err);
if (strcmp(argv[1], "lit") == 0) {
// For Rules
TransPar par;
get_args(par, argc, argv); // get arguments
gen_rules(par); // generate rules (really, just transactions)
}
else if (strcmp(argv[1], "seq") == 0) {
// For Sequences
SeqPar par;
get_args(par, argc, argv); // get arguments
gen_seq(par); // generate sequences
}
else if (strcmp(argv[1], "tax") == 0) {
// For Rules with Taxonomies
TaxPar par;
get_args(par, argc, argv); // get arguments
gen_taxrules(par); // generate rules (really, just transactions)
}
else if (strcmp(argv[1], "-version") == 0) {
print_version();
return 0;
}
else {
cerr << "Synthetic Data Generation, ";
print_version();
cerr << "Usage: " << argv[0] << " lit|tax|seq [options]\n";
cerr << " " << argv[0]
<< " lit|tax|seq -help For more detailed list of options\n";
return 1;
}
return 0;
}
Also I should mentioned the source code was built for Unix but I modified it for running to win.
You need to check if argc >= 2 before using argv[1]. If the user doesn't supply any arguments then you are accessing an argument that doesn't exist.
According to the C and C++ standards, argv[argc] is guaranteed to be a null pointer, which is what you're seeing here; you're passing a null pointer to strcmp() and this is causing the crash. (Side note: accessing argv[argc + 1] is undefined behavior so you need to be especially careful when accessing indices 2+.)

Variable length and position command line arguments

So, quick question:
I am tasked with making a program that reads in a file, does some fancy things, and writes out to an html file with the re-purposed text, all simple stuff.
Furthermore the program must be able to accept up to four command line arguments (but a minumum of two). The executable of course, the file it is reading in, the file name it will be reading out to, and finally a "-r" argument for more information on the file (the amount of paragraphs, etc).
So the question I have is as follows:
the "-r" argument can be anywhere in the arguments (as long as it comes after argv[0] of course), or it can be completely non-existent (as can the output file name).
This is still simple to do, a little tedious writing a bunch of if's or even a switch or two, but I can't help but think that there may be an easier way to accomplish this, rather than having a plethora of if statements.
Any help would be greatly appreciated. (I also suppose you don't need any code considering I don't exactly have a problem.)
Here is roughly how one might do it without a library:
GCC 4.8.2: g++ -Wall -Wextra -std=c++0x main.cpp
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
char* input = nullptr;
char* output = nullptr;
char* r_arg = nullptr;
--argc; ++argv; // Skip the program name.
const char* def_in = "default in";
const char* def_out = "default out";
const char* def_r = "default r";
while (0 < argc) {
if (std::string(argv[0]) == "-r") {
// This code requires a space after the "-r", which is unusual.
++argv;
--argc;
r_arg = argv[0]; }
else if (input == nullptr) {
input = argv[0]; }
else if (output == nullptr) {
output = argv[0]; }
else {
std::cerr << "error: unexpected arg '" << argv[0] << "'\n"; }
++argv;
--argc; }
if (input == nullptr) {
input = const_cast<char*>(def_in); }
if (output == nullptr) {
output = const_cast<char*>(def_out); }
if (r_arg == nullptr) {
r_arg = const_cast<char*>(def_r); }
std::cout << "input: " << input << "\n"
<< "output: " << output << "\n"
<< "r arg: " << r_arg << "\n";
return 0; }