Mastering main(int argc, char **argv) - kevshouse/exam_quest GitHub Wiki
This document contains a series of exercises designed to build your confidence and skill in handling command-line arguments in C. Each exercise focuses on a common pattern you might encounter in 42 School exams and other C programming challenges.
Goal: To become proficient in parsing, validating, and using the argc
and argv
parameters.
Tools Allowed: For these exercises, restrict yourself to the write
function from <unistd.h>
for all output. You may use <stdlib.h>
for atoi
where specified.
Objective: Write a program that prints the number of arguments it received.
File: arg_count.c
Logic:
- The program should take any number of arguments.
- It should print a single digit character representing the number of arguments (including the program name).
- Follow the output with a newline character.
Hint: argc
is an integer. To print it with write
, you must convert it to a character. For single digits, you can do this by adding the ASCII value of '0'.
Example Usage:
$> ./arg_count
1
$> ./arg_count hello world
3
$> ./arg_count "one arg"
2
Objective: Write a program that prints each argument on a new line.
File: print_args.c
Logic:
- The program should iterate through the
argv
array. - For each string in
argv
(starting fromargv[1]
), print the string to the console. - Each argument should be followed by a newline character.
- If there are no arguments (other than the program name), the program should print nothing.
Hint: You will need a function to calculate the length of a string to use write
correctly.
Example Usage:
$> ./print_args See you later alligator
See
you
later
alligator
$> ./print_args
$>
Objective: Write a program that prints the arguments in reverse order.
File: rev_args.c
Logic:
- This is similar to "Print Arguments," but you should iterate through
argv
backwards. - Start from the last argument (
argv[argc - 1]
) and go down toargv[1]
. - Print each argument, followed by a newline.
Example Usage:
$> ./rev_args See you later alligator
alligator
later
you
See
Objective: Recreate a basic version of the echo
command that supports the -n
flag to suppress the trailing newline.
File: my_echo.c
Logic:
- Check if the first argument (
argv[1]
) is exactly"-n"
. - If it is, print all subsequent arguments (
argv[2]
,argv[3]
, etc.), separated by a single space. Do not print a final newline. - If the first argument is not
"-n"
, print all arguments (argv[1]
,argv[2]
, etc.), separated by a single space, and then print a final newline.
Example Usage:
$> ./my_echo hello world
hello world
$> ./my_echo -n hello world
hello world$> # Note the lack of a newline
$> ./my_echo -n
$>
$> ./my_echo
Good luck! Completing these will give you a strong foundation for more complex problems like do_op
, search_and_replace
, and even ft_split
.