getcwd: port to mingw
[gnulib.git] / tests / test-getcwd.c
1 /* Test of getcwd() function.
2    Copyright (C) 2009 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #include <config.h>
18
19 #include <unistd.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #define ASSERT(expr) \
26   do                                                                         \
27     {                                                                        \
28       if (!(expr))                                                           \
29         {                                                                    \
30           fprintf (stderr, "%s:%d: assertion failed\n", __FILE__, __LINE__); \
31           fflush (stderr);                                                   \
32           abort ();                                                          \
33         }                                                                    \
34     }                                                                        \
35   while (0)
36
37 int
38 main (int argc, char **argv)
39 {
40   char *pwd1;
41   char *pwd2;
42   /* If the user provides an argument, attempt to chdir there first.  */
43   if (1 < argc)
44     {
45       if (chdir (argv[1]) == 0)
46         printf ("changed to directory %s\n", argv[1]);
47     }
48
49   pwd1 = getcwd (NULL, 0);
50   ASSERT (pwd1 && *pwd1);
51   if (1 < argc)
52     printf ("cwd=%s\n", pwd1);
53
54   /* Make sure the result is usable.  */
55   ASSERT (chdir (pwd1) == 0);
56   ASSERT (chdir ("././.") == 0);
57
58   /* Make sure that result is normalized.  */
59   pwd2 = getcwd (NULL, 0);
60   ASSERT (pwd2);
61   ASSERT (strcmp (pwd1, pwd2) == 0);
62   free (pwd2);
63   {
64     size_t len = strlen (pwd1);
65     size_t i = len - 10;
66     if (i < 0)
67       i = 0;
68     pwd2 = malloc (len + 2);
69     for ( ; i < len; i++)
70       ASSERT (getcwd (pwd2, i) == NULL);
71     pwd2 = getcwd (pwd2, len + 1);
72     ASSERT (pwd2);
73     pwd2[len] = '/';
74     pwd2[len + 1] = '\0';
75   }
76   ASSERT (strstr (pwd2, "/./") == NULL);
77   ASSERT (strstr (pwd2, "/../") == NULL);
78
79   free (pwd1);
80   free (pwd2);
81
82   return 0;
83 }