Skip to content

Commit c2c3cd7

Browse files
committed
posix getcwd: split from main
1 parent 6e19044 commit c2c3cd7

File tree

3 files changed

+27
-21
lines changed

3 files changed

+27
-21
lines changed

posix/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
1. [gethostbyname](gethostbyname.c)
3535
1. [gethostname](gethostname.c)
3636
1. [getservbyport](getservbyport.c)
37+
1. Process information
38+
1. [getcwd](getcwd.c)
3739
1. Signal
3840
1. [Kill](kill.c)
3941
1. Interactive

posix/getcwd.c

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/* https://stackoverflow.com/questions/16285623/pwd-to-get-path-to-the-current-file/54155296#54155296 */
2+
3+
#define _XOPEN_SOURCE 700
4+
#include <assert.h>
5+
#include <stdlib.h>
6+
#include <stdio.h>
7+
#include <unistd.h>
8+
9+
int main(void) {
10+
long n;
11+
char *buf;
12+
13+
n = pathconf(".", _PC_PATH_MAX);
14+
assert(n != -1);
15+
buf = malloc(n * sizeof(*buf));
16+
assert(buf);
17+
if (getcwd(buf, n) == NULL) {
18+
perror("getcwd");
19+
exit(EXIT_FAILURE);
20+
} else {
21+
printf("%s\n", buf);
22+
}
23+
free(buf);
24+
return EXIT_SUCCESS;
25+
}

posix/main.c

-21
Original file line numberDiff line numberDiff line change
@@ -1211,27 +1211,6 @@ int main(void) {
12111211
printf("geteuid() = %ju\n", (uintmax_t)euid );
12121212
printf("getegid() = %ju\n", (uintmax_t)egid );
12131213
printf("getppid() = %ju\n", (uintmax_t)getppid());
1214-
1215-
/*
1216-
# getcwd
1217-
1218-
pwd
1219-
1220-
# root directory
1221-
1222-
As of POSIX 7, this concept is not available.
1223-
1224-
It is implemented as a Glibc extension under `_BSD_SOURCE`.
1225-
*/
1226-
{
1227-
const int n = 1 << 10;
1228-
char buf[n];
1229-
if (getcwd(buf, n) == NULL) {
1230-
perror("getcwd");
1231-
} else {
1232-
printf("getcwd() = %s\n", buf);
1233-
}
1234-
}
12351214
}
12361215

12371216
/*

0 commit comments

Comments
 (0)