Dungeoun Dungeoun - 22 days ago 7
C++ Question

c++: How to run a program taking string and filenames as arguments?

I've to run a program sample

sample-code.cpp
. It is taking a string like
-create
, 2 file names: one as input
input.txt
and one as output filename
output.idx
as parameters and one integer
10
.

I should be able to run it from command line (mac Terminal/UNIX) using:

$sample-code -create input.txt output.txt 10


This is a snippet of
main()
code:

int main(int argc, char* argv[])
{

// Creating New File
if (strcmp(argv[1],"-create") == 0)
{
KeyFieldMax = atoi(argv[2]);
InputFileName = argv[3];
IndexFileName = argv[4];


when I type this command
$sample-code -create input.txt output.txt 10
I get this error :

-bash: sample-code: command not found
.

Answer

bash: sample-code: command not found is telling you that sample-code is not in bash's command path. if you're in the directory you build the program in, type ./sample-code to run it.

Your error Segmentation fault: 11 is an out of bounds array. You need to run a sanity check on the arguments to verify they are actually there before calling their position in the array:

if (argc < 4)
{
    fprintf(stderr, "Urk! Not enough arguments!");
    return 1;
}
else
{
    KeyFieldMax = atoi(argv[2]);
    InputFileName = argv[3];
    IndexFileName = argv[4];
    ...