A collection of simple Unix command-line utilities implemented in C, mimicking the behavior of standard Unix tools.
| Utility | Description |
|---|---|
pwd |
Print the current working directory |
echo |
Print arguments to standard output |
cp |
Copy a file to a destination |
mv |
Move/rename a file to a destination |
unix-utilities/
├── pwd.cpp
├── echo.cpp
├── cp.cpp
├── mv.cpp
└── README.md
Files use the
.cppextension due to a platform limitation, but are written in pure C.
Each utility is compiled separately using gcc:
gcc -o pwd pwd.cpp
gcc -o echo echo.cpp
gcc -o cp cp.cpp
gcc -o mv mv.cppOr compile all at once:
for f in pwd echo cp mv; do gcc -o $f $f.cpp; donePrints the absolute path of the current working directory.
$ ./pwd
/home/user/unix-utilitiesPrints all arguments to stdout, space-separated, with a trailing newline.
$ ./echo Hello World
Hello World
$ ./echo
(blank line)Copies a source file to a destination path. Creates the destination if it does not exist; truncates it if it does. Preserves the source file's permissions.
$ echo "Hello" > file.txt
$ ./cp file.txt /tmp/file_copy.txt
$ cat /tmp/file_copy.txt
HelloError case:
$ ./cp nonexistent.txt /tmp/out.txt
cp: cannot open source: No such file or directoryMoves a file to a new location or renames it. Uses rename() for same-filesystem moves (atomic, instant). Falls back to copy + delete for cross-device moves.
$ echo "Hello" > /tmp/file.txt
$ ./mv /tmp/file.txt /tmp/new_name.txt
$ cat /tmp/new_name.txt
Hello
$ ls /tmp/file.txt
ls: cannot access '/tmp/file.txt': No such file or directoryCross-device move:
$ ./mv /tmp/file.txt /home/user/file.txt
(file is copied to destination, then removed from source)Error case:
$ ./mv nonexistent.txt /tmp/out.txt
mv: No such file or directory| Utility | Key calls |
|---|---|
pwd |
getcwd(), free() |
echo |
printf() |
cp |
open(), fstat(), read(), write(), close() |
mv |
rename(), stat(), open(), read(), write(), close(), unlink() |
- All error messages are printed to
stderrusingperror()orfprintf(stderr, ...) - All system call return values are checked
mvhandles cross-device moves transparently via a copy-then-delete fallback (triggered whenrename()returnsEXDEV)cpandmvpreserve source file permissions on the destination