This will be how we send input to the shell essentially. For this portion, we need a way to read input.
This is similar to this section on File Operations.
However, we need a way to read input line by line that works well in a shell.
- There are a few ways of doing this:
scanf()
fgets()
getline()
scanf
vs fgets
vs getline
scanf("%s")
- Does not allocate memory dynamically — you must provide a fixed-size buffer.
- Stops reading at the first whitespace, so it can’t capture multi-word input.
- Risk of buffer overflow if you don’t specify a maximum width.
- Does not remove the newline character because it stops before it anyway.
- Example: typing
ls -l /home
will only store "ls"
and ignore the rest.
fgets()
- Requires you to provide a fixed-size buffer.
- Reads spaces, so it can capture multi-word input.
- Stops reading when it reaches a newline or when the buffer is full (whichever comes first).
- If the line is longer than your buffer, the rest of the input stays in stdin for the next read.
- Keeps the newline character (
'\\n'
) at the end of the string, so you may need to remove it manually.
- Safer than
scanf
because you can control the maximum characters read.