Unix Tools

Implementations of common Unix command-line utilities written in C.


unix-tools / pwd.c

pwd.c raw | download
1#define _POSIX_C_SOURCE 200809L
2#include <unistd.h>
3#include <errno.h>
4#include <stdint.h>
5#include <stdio.h>
6#include <stdlib.h>
7
8int
9main(int argc, char **argv)
10{
11 size_t size = 128;
12 char *path;
13 if (argc != 1) { fprintf(stderr, "usage: %s\n", argv[0]); return 1; }
14 for (;;) {
15 path = malloc(size);
16 if (path == NULL) { perror("pwd: malloc"); return 1; }
17 if (getcwd(path, size) != NULL) break;
18 {
19 int saved = errno;
20 free(path);
21 errno = saved;
22 }
23 if (errno != ERANGE) { perror("pwd: getcwd"); return 1; }
24 if (size > SIZE_MAX / 2) { fprintf(stderr, "pwd: path too long\n"); return 1; }
25 size *= 2;
26 }
27 if (puts(path) == EOF || fflush(stdout) == EOF) {
28 perror("pwd: stdout"); free(path); return 1;
29 }
30 free(path);
31 return 0;
32}