C no evil
Lab exercises: Due January 30th 5PM (24 hr late period allowed)
The goals for this assignment are:
-
Working with stdout and stderr
-
Working with environment variables
-
Working with C strings
To get started, clone the repository here
1. stdout, stderr
Write a program, outerr.c
, that outputs the even integers between 0 and 10 to standard out
and the odd integers between 1 and 10 to standard error.
$ ./outerr
0
1
2
3
4
5
6
7
8
9
$ ./outerr > even.txt 2> odd.txt
$ cat even.txt
0
2
4
6
8
$ cat odd.txt
1
3
5
7
9
2. Environment
Write a program, myenv.c
, that loops through the process’s environment variables and
prints the value for PATH. Use the code below, based on pointer arithmetic,
as a starting point.
int main(int argc, char** argv, char** envp)
{
while(*envp)
{
printf("%s\n",*envp++);
}
}
$ ./myenv
PATH=/home/alinen/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$ env | grep PATH
PATH=/home/alinen/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
The shell command env prints the environment
|
The paths above were truncated for brevity. Yours will be much longer! |
3. Advanced C strings
In assignment 02, you need to dynamically allocate a list of command line arguments.
For example, if the command line is ls -l -a
, you need to create a null-terminated
list of strings, [ls, -l, -a, NULL]
.
In the file, argv.c
, implement a program that tokenizes a string into
a null-terminated array of strings created dynamically with malloc.
Then implement a function to print the array of strings using pointer arithmetic.
$ ./argv
[ls, -l, -a, NULL]
Requirements/Hints:
-
Use
strtok
to tokenize a string. -
Use malloc and free to create the list you pass to print.
-
Do not store the length of the list of strings.
-
Use valgrind to make sure you do not have memory leaks.
-
Do not use standard template library data structures.
4. Stack diagram
Draw a stack diagram for the program argv.c
.
5. Submission
-
Hand-in the stack diagram for your team.
-
One team member (or both) should submit their code.
5.1. Submit your work to Github
Add and check in your program using git and then push your changes to Github.
Run the following command inside your labs-USERNAME
directory.
$ cd labs-USERNAME
$ git add .
$ git commit -m "Descriptive message"
$ git push
Run git status
to check the result of the previous git command.
Check the Github website to make sure that your program uploaded correctly.