How to create files given relative path [duplicate] - c++

This question already has answers here:
Creating files in C++
(8 answers)
Closed 8 years ago.
I have a path given in command line with a filename in it like:
./something.bin infomration /some/some2/thing.txt
I know I can put the /some/some2/thing.txt into a global variable and use it. Now, I want to:
create a file named thing.txt in the path /some/some2/

For things like this you'll have to use the parameters passed to your main entry point:
int main(int argc, char **argv) {
// some other code
return 0;
}
As you can see, main() will receive two parameters:
argc: The first parameter will include the number of parameters passed through the second parameter.
argv: The second parameter points to pointers that point to strings with the actual parameters.
The usage is quite trivial, but it's important to remember that the very first "argument" is the executable file itself.
In your example, argc would be set to 3 and argv would point to the following strings:
argv[0]: ./something.bin (based on the OS, this could also be an absolute path)
argv[1]: infomration [sic]
argv[2]: /some/some2/thing.txt
As you can see, all you'll have to do is the following:
Verify the number of arguments is correct.
Verify the second argument (infomration) is correct.
Use the third argument to receive the actual file name.
Keep in mind that the user might pass invalid parameters (e.g. invalid characters for a file name) or he might try to trick you into doing something you shouldn't do (like passing reserved names).

Related

Define a variable in a shell script that is passed as a command line argument to c++ executable [duplicate]

Everytime I create a project (standard command line utility) with Xcode, my
main function starts out looking like this:
int main(int argc, const char * argv[])
What's all this in the parenthesis? Why use this rather than just
int main()?
main receives the number of arguments and the arguments passed to it when you start the program, so you can access it.
argc contains the number of arguments, argv contains pointers to the arguments.
argv[argc] is always a NULL pointer. The arguments usually include the program name itself.
Typically if you run your program like ./myprogram
argc is 1;
argv[0] is the string "./myprogram"
argv[1] is a NULL pointer
If you run your program like ./myprogram /tmp/somefile
argc is 2;
argv[0] is the string "./myprogram"
argv[1] is the string "/tmp/somefile"
argv[2] is a NULL pointer
Although not covered by standards, on Windows and most flavours of Unix and Linux, main can have up to three arguments:
int main(int argc, char *argv[], char *envp[])
The last one is similar to argv (which is an array of strings, as described in other answers, specifying arguments to the program passed on the command line.)
But it contains the environment variables, e.g. PATH or anything else you set in your OS shell. It is null terminated so there is no need to provide a count argument.
These are for using the arguments from the command line -
argc contains the number of arguments on
the command line (including the program name), and argv is the list of
actual arguments (represented as character strings).
These are used to pass command line paramters.
For ex: if you want to pass a file name to your process from outside then
myExe.exe "filename.txt"
the command line "filename.txt" will be stored in argv[], and the number of command line parameter ( the count) will be stored in argc.
main() is a function which actually can take maximum three parameters or no parameters.
The following are the parameters that main() can take is as follows:-
1) int argc : It holds the number of arguments passed (from the command prompt) during the execution of program or you can say it is used ot keep a track of the number of variables passed during the execution of program. It cannot hold the negative value. Eg. If you pass your executable file "./a.out" then that will be considered as a parameter and hence argc value will be 0 i.e 1 value is passed.
2) char *argv[] : it is an array of character pointers which holds the address of the strings(array of characters) that are passed from the command prompt during execution of program. Eg. in above example if you wrote argv[argc] i.e argv[0] in cout then it will give ./a.out as output.
3) char*envp[] : it is also an array of character pointer which is used to hold the address of the environments variables being used in the program. Environment variables are the set of dynamic named value that can affect the way the running process will behave on the computer. For example running process want to store temporary files then it will invoke TEMP environment variables to get a suitable location.

How much memory is allocated for argv[]? [duplicate]

This question already has answers here:
where command line arguments are stored?
(4 answers)
Closed 6 years ago.
I know that the command line arguments are character arrays and that they are stored on the stack. But, I want to know actual memory allocation for of each argument. e.g. suppose I passed the directory name "/tmp" as a command line argument. This will be stored in argv[1]. But as I tested, it is allowed to change argv[1] to "/tmp/log/" (size increased) in the program. How is this possible ?
To answer your question, the total maximum size available to argument strings and the passed environment can be obtained with:
getconf ARG_MAX
from the command line or the syconf equivalent from C (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/limits.h.html for more information).
(On my Linux box, the limit is 2097152).
Your example happens to work because the arguments and the environment are realistically stored contiguously, so appending to a string will overwrite what comes after it (following arguments, or the environment).
And that's why it's a bad idea to try and expand the argv strings like that. If you want to modify them, either edit them or shrink them, but trying to expand them is a call for trouble.
On Linux, parameters are populated by create_elf_tables. For this specific platform at least, you are correct that the values are stored on the stack.
Linux only uses exactly as much memory as is necessary to store arguments and (initial) environment variables on the stack; if you try to use more than what is already there, you're overwriting something else (or crashing).
The standard states that the argv can be modified since it is a special internal.
177 — The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination, so it is allocated only what you need at the assignment or replacement.
Standard text:
http://c0x.coding-guidelines.com/5.1.2.2.1.html

How to read arguments from target [duplicate]

This question already has answers here:
Reading command line parameters
(4 answers)
Closed 9 years ago.
When you right click on a program in windows(such as starcraft.exe) and look at its properties there is a text field called "target" which contains the full path of the binary. I have seen programs able to parse flags added to the target such as "C:\programfiles\myprogram\myprogram.exe -x 1280 -y 360" and the program would start up in the specified resolution. My question is how to read those arguments, if it is done by argv[] please just inform me of my stupidity.
C++ is the language, VS express 2012 desktop is the environment.
you receive those parameters when calling executable main method int main(int argc, char* argv[]) as argc (count) and argv[] parameters all you have to do is just parse them
here is an example How to parse command line parameters
You'll want to avoid comparisons between char* and string literals without strncmp.
Remember that argc is the the argument count (including the program name).
argv is an array of C strings specifying the arguments (first being the program name as invoked).
In this case, you're usually best off using a library, like getopt. This will make interleaved options, long options, and arguments much more sane to manage (assuming order between options and arguments is largely unimportant).

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

This question already has answers here:
Closed 11 years ago.
Duplicate:
What is the proper declaration of main?
What do we mean by the arguments in this main function? What are they trying to tell us?
int main(int argc, char** argv)
UPDATE: And, is the preceding line of code similar to this int main(int argc, char* argv[])? If so, how can we say that char** argv is similar to char* argv[] as they don't look similar from an array point of view?
How is it compared with int main() which does not have any arguments?
Thanks.
The argc parameter is the number of command line options specified, including the executable name, when the executable was invoked. The individual command line options are found in the argv array, which is NULL terminated (the name and path used to invoke the executable is in argv[0]).
The difference between the two versions is simply if you want to parse command line arguments or not - if you are not interested in them then you can ignore them using the second form.
Wikipedia offers a good explanation. The first parameter gives you the number of command line arguments, and the second gives you the actual arguments.
They represent the command line parameters.
argc is the number of command line parameters, including the name of the executable.
argv is an array of null-terminated strings, where argv[0] is the command line parameter, and argv[i] is the ith parameter after that, argv[argc-1] being the last one and argv[argc] is actually well defined and a NULL pointer.
Thus:
foo bar baz
on the command line will have argc=3, argv[0]="foo" argv[1]="bar" argv[2]="baz" argv[3] = NULL
Note that there is no special attachment placed for "flag" arguments.
grep -i foo bar.cpp bar.h
would have 4 arguments (argc=5 including grep itself), -i being one of them and this would apply even if the next parameter was a "value" attached to the flag.
Note if you did a wildcard
grep -i foo *
in UNIX at least, the * would be expanded before the call into grep and thus each file that matched would be an argument.
Incidentally
char** argv and char* argv[]
do the same thing.
Also while the standard says you must use one of these signatures (you shouldn't even add in any consts) there is no law you have to use those two variable names, but it is so conventional now that they are pretty much universal. (i.e. you could use argCount and argValues if you want).
argc gives you the number of arguments and argv gives you those arguments. The first one is the path to the .exe used to run your program, the following ones are arguments the caller of your .exe provided on the command line like this:
my.exe arg1 arg2
Whereas
int main() {}
just ignores the arguments.
argv is an array holding the commandline parameters passed to the application. argc tells you the number of elements contained in that array.

Why check if (*argv == NULL)? [duplicate]

This question already has answers here:
When can argv[0] have null?
(4 answers)
Closed 6 years ago.
In the data structures class that I am currently taking, we have been tasked with writing a web crawler in C++. To give us a head start, the professor provided us with a program to get the source from a given URL and a simple HTML parser to strip the tags out. The main function for this program accepts arguments and so uses argc/argv. The code used to check for the arguments is as follows:
// Process the arguments
if (!strcmp(option, "-h"))
{
// do stuff...
}
else if (!strcmp(option, ""))
{
// do stuff...
}
else if (!strcmp(option, "-t"))
{
// do stuff...
}
else if (!strcmp(option, "-a"))
{
// do stuff...
}
if ( *argv == NULL )
{
exit(1);
}
Where "option" has been populated with the switch in argv[1], and argv[2] and higher has the remaining arguments. The first block I understand just fine, if the switch equals the string do whatever based on the switch. I'm wondering what the purpose of the last if block is though.
It could be that my C++ is somewhat rusty, but I seem to recall *argv being equivalent to argv[0], basically meaning it is checking to make sure arguments exist. Except I was under the impression that argv[0] always (at least in most implementations) contained the name of the program being run. It occurs to me that argv[0] could be null if argc is equal to 0, but searching around on Google I couldn't find a single post determining whether or not that is even possible.
And so I turn to you. What exactly is that final if block checking?
EDIT: I've gone with the reasoning provided in the comments of the selected answer, that it may be possible to intentionally cause argv[0] to become NULL, or otherwise become NULL based on an platform-specific implementation of main.
3.6.1/2:
If argc is non-zero those arguments
shall be provided in argv[0] though
... and argv[0] shall be the pointer
to the initial character of a NTMBS
that represents the name used to
invoke the program or "". The value of
argc shall be nonnegative. The value
of argv[argc] shall be 0.
Emphasis mine. argc is only guaranteed non-negative, not non-zero.
This is at entry to main. It's also possible that //do stuff modifies the value of argv, or the contents of the array it points to. It's not entirely unheard of for option-handling code to shift values off argv as it processes them. The test for *argv == null may therefore be testing whether or not there are any command-line arguments left, after the options have been removed or skipped over. You'd have to look at the rest of the code.
argc will provide you with the number of command line arguments passed. You shouldn't need to check the contents of argv too see if there are not enough arguments.
if (argc <= 1) { // The first arg will be the executable name
// print usage
}
Remembering just how portable C is, it might not always be running on a standard platform like Windows or Unix. Perhaps it's some micro-code inside your washing machine running on some cheap, hacked environment. As such, it's good practice to make sure a pointer isn't null before dereferencing it, which might have led to the question.
Even so, you're correct. *argv is the same as argv[0], and argv is supposed to be initialized by the environment, if it's provided.
just a speculation.
what if your professor is referring to this ??
while(*++argv !=NULL)
printf("%s\n",*argv);