C MoreLesson 56Free preview
C Command-Line Args
This lesson is part of C · All levels
Summary
The play function can receive arguments from the command row through int main(int argc, char *argv[]), where argc is the number of arguments and argv is the array string of arguments. argv[0] usually contains the name of the program so the user argument starts with argv[1]. Since all arguments are string-shaped, convert to a number with strtol, atoi, or sscanf before using the count.
Key points
- Argc is always a minimum of 1, and argv[argc] is guaranteed to be worth NULL as the end marker of the list.
- Argv[0] contains the name or path of the program, while the user argument begins with argv[1].
- Parsing numbers should be using a strtol that can detect errors, not a failure-witness tool.
- The general format of an argument-based program is the option to pass data, e.g. the program -v file.txt.
- Check the options using strcmp, for example strcmp(argv[1], "-h") == 0.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.