1 /*
2  * $Id: dir.c,v 1.1 2005-09-18 22:05:35 dhmunro Exp $
3  * MS Windows version of plib directory operations
4  */
5 /* Copyright (c) 2005, The Regents of the University of California.
6  * All rights reserved.
7  * This file is part of yorick (http://yorick.sourceforge.net).
8  * Read the accompanying LICENSE file for details.
9  */
10 
11 #include "config.h"
12 #include "pstdlib.h"
13 #include "pstdio.h"
14 #include "playw.h"
15 
16 #include <string.h>
17 
18 struct p_dir {
19   HANDLE hd;
20   int count;
21   WIN32_FIND_DATA data;
22 };
23 
24 p_dir *
p_dopen(const char * unix_name)25 p_dopen(const char *unix_name)
26 {
27   char *name = w_pathname(unix_name);
28   p_dir *dir = p_malloc(sizeof(p_dir));
29   int i = 0;
30   while (name[i]) i++;
31   if (i>0 && name[i-1]!='\\') name[i++] = '\\';
32   name[i++] = '*';
33   name[i++] = '\0';
34   dir->hd = FindFirstFile(name, &dir->data);
35   if (dir->hd != INVALID_HANDLE_VALUE) {
36     /* even empty directories contain . and .. */
37     dir->count = 0;
38   } else {
39     p_free(dir);
40     dir = 0;
41   }
42   return dir;
43 }
44 
45 int
p_dclose(p_dir * dir)46 p_dclose(p_dir *dir)
47 {
48   int flag = -(!FindClose(dir->hd));
49   p_free(dir);
50   return flag;
51 }
52 
53 char *
p_dnext(p_dir * dir,int * is_dir)54 p_dnext(p_dir *dir, int *is_dir)
55 {
56   for (;;) {
57     if (dir->count++) {
58       if (!FindNextFile(dir->hd, &dir->data))
59         return 0;   /* GetLastError()==ERROR_NO_MORE_FILES or error */
60     }
61     if (dir->data.cFileName[0]!='.' ||
62         (dir->data.cFileName[1] && (dir->data.cFileName[1]!='.' ||
63                                     dir->data.cFileName[2]))) break;
64   }
65   *is_dir = ((dir->data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) != 0);
66   return (char *)dir->data.cFileName;
67 }
68 
69 int
p_chdir(const char * dirname)70 p_chdir(const char *dirname)
71 {
72   const char *path = w_pathname(dirname);
73   /* is this necessary?
74   if (path[0] && path[1]==':' &&
75       ((path[0]>='a' && path[0]<='z') || (path[0]>='A' && path[0]<='Z'))) {
76     char drive[8];
77     drive[0] = *path++;
78     drive[1] = *path++;
79     drive[2] = '\0';
80     if (!SetCurrentDrive(drive)) return -1;
81   }
82   */
83   return -(!SetCurrentDirectory(path));
84 }
85 
86 int
p_rmdir(const char * dirname)87 p_rmdir(const char *dirname)
88 {
89   return -(!RemoveDirectory(w_pathname(dirname)));
90 }
91 
92 int
p_mkdir(const char * dirname)93 p_mkdir(const char *dirname)
94 {
95   return -(!CreateDirectory(w_pathname(dirname), 0));
96 }
97 
98 char *
p_getcwd(void)99 p_getcwd(void)
100 {
101   DWORD n = GetCurrentDirectory(P_WKSIZ, p_wkspc.c);
102   if (n>P_WKSIZ || n==0) return 0;
103   return w_unixpath(p_wkspc.c);
104 }
105