Some Code for the Project
- Current Working Directory
- Each process has a "current working directory"
- Relative paths are computed from here.
- It is inherited from the parent process.
- The bash maintains a variable (PWD) contains this value
- But this is part of bash
- cd is a bash built-in command
- It is also an executable.
- pwd
- This is both a bash built in and an executable.
- Both will display the current working directory.
- A process can get the value of the working directory
- char *getcwd(char *buf, size_t size);
- Copies the absolute pathname to buf if buf is big enough.
- If buf is NULL, it will allocate a buffer for the name
- Which the user should free.
- Returns a pointer to the buffer on success, or NULL on failure
- A process can change the working directory as well:
- int chdir(const char *path);
- Returns -1 on error and 0 on success.
- Changes the CWD to path (if it can)
- if path starts with / it is absolute
- otherwise it is relative.
- ~ does not work here (that is a shell function)
- There are two tools for parsing the directory name.
- #include <libgen.h>
- char *dirname(char *path);
- char *basename(char *path);
- Be careful, these alter path.
- They may change the final / in path to be a \0
- Thus multiple calls to dirname can make a mess of things.
- They may make a copy of path and return a pointer to statically allocated memory
- Which may be overwritten by later calls.
- Paths like "/bin/" have been a problem in the past.
- But a trailing / no longer counts.
- basename returns a pointer to everything after the last /
- dirname returns a pointer to everything before the last /
- If the path does not contain a /, then dirname returns a .
- If the path is / both return /
- If path is NULL or "" both return a .
- There are apparently two versions of basename, depending on if you include <libgen.h> or not.