This repository contains a simple argument parser implementation in C. The parser supports parsing command-line options and positional arguments, providing a flexible framework for handling various types of inputs. I'm making this mainly to use for 42 Mastery projects where a lot of projects require parsing arguments.
- GCC or any C compiler.
- Basic understanding of command-line argument parsing.
To compile the program, run the following command:
gcc -o argparse argparse.cHere is an example usage of the compiled program:
./argparse -v -c 5 -n "Example Name" arg1 arg2 arg3Verbose: 1
Count: 5
Name: Example Name
Positional arguments:
arg1
arg2
arg3- Option Structure (
Option):- Defines the flags, their types, and associated values.
- Argument Parser (
ArgParser):- Manages the list of options and positional arguments.
- Initialization and Parsing Functions:
init_arg_parser: Initializes the parser.add_option: Adds a new option to the parser.parse_arguments: Parses command-line arguments and assigns values to the appropriate variables.
Use the add_option function to define options:
add_option(&parser, "-v", "--verbose", ARGTYPE_FLAG, &verbose);
add_option(&parser, "-c", "--count", ARGTYPE_INT, &count);
add_option(&parser, "-n", "--name", ARGTYPE_STRING, &name);-v/--verbose: A flag option that setsverboseto1when provided.-c/--count: An integer option that assigns a value tocount.-n/--name: A string option that assigns a value toname.
Call parse_arguments with argc and argv:
parse_arguments(&parser, argc, argv);This function matches provided arguments against the defined options and handles positional arguments.
Use the print_usage function to display all supported options:
print_usage(&parser);- Maximum of 20 options and 20 positional arguments (can be adjusted by modifying
MAX_OPTIONSandMAX_POSITIONAL). - Does not support default values for options.
- No advanced error handling for malformed arguments.
Contributions are welcome! Feel free to open issues or submit pull requests to improve this project.
This project is licensed under the MIT License. See the LICENSE file for details.