xref: /reactos/sdk/lib/crt/stdlib/senv.c (revision 50cf16b3)
1 /*
2  * COPYRIGHT:   See COPYING in the top level directory
3  * PROJECT:     ReactOS system libraries
4  * FILE:        lib/sdk/crt/stdlib/senv.c
5  * PURPOSE:     Unknown
6  * PROGRAMER:   Unknown
7  * UPDATE HISTORY:
8  *              25/11/05: Added license header
9  */
10 
11 #include <precomp.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <tchar.h>
15 
16 #ifdef _UNICODE
17    #define sT "S"
18 #else
19    #define sT "s"
20 #endif
21 
22 #define MK_STR(s) #s
23 
24 /*
25  * @implemented
26  */
27 void _tsearchenv(const _TCHAR* file,const _TCHAR* var,_TCHAR* path)
28 {
29     _TCHAR* env = _tgetenv(var);
30     _TCHAR* x;
31     _TCHAR* y;
32     _TCHAR* FilePart;
33 
34     TRACE(MK_STR(_tsearchenv)"()\n");
35 
36     x = _tcschr(env,'=');
37     if ( x != NULL ) {
38         *x = 0;
39         x++;
40     }
41     y = _tcschr(env,';');
42     while ( y != NULL ) {
43         *y = 0;
44         if ( SearchPath(x,file,NULL,MAX_PATH,path,&FilePart) > 0 ) {
45             return;
46         }
47         x = y+1;
48         y = _tcschr(env,';');
49     }
50     return;
51 }
52 
53 /*********************************************************************
54  *		_searchenv_s (MSVCRT.@)
55  */
56 int _tsearchenv_s(const _TCHAR* file, const _TCHAR* env, _TCHAR *buf, size_t count)
57 {
58   _TCHAR *envVal, *penv;
59   _TCHAR curPath[MAX_PATH];
60 
61   if (!MSVCRT_CHECK_PMT(file != NULL) || !MSVCRT_CHECK_PMT(buf != NULL) ||
62       !MSVCRT_CHECK_PMT(count > 0))
63   {
64       *_errno() = EINVAL;
65       return EINVAL;
66   }
67 
68   *buf = '\0';
69 
70   /* Try CWD first */
71   if (GetFileAttributes( file ) != INVALID_FILE_ATTRIBUTES)
72   {
73     GetFullPathName( file, MAX_PATH, buf, NULL );
74     _dosmaperr(GetLastError());
75     return 0;
76   }
77 
78   /* Search given environment variable */
79   envVal = _tgetenv(env);
80   if (!envVal)
81   {
82     _set_errno(ENOENT);
83     return ENOENT;
84   }
85 
86   penv = envVal;
87 
88   do
89   {
90     _TCHAR *end = penv;
91 
92     while(*end && *end != ';') end++; /* Find end of next path */
93     if (penv == end || !*penv)
94     {
95       _set_errno(ENOENT);
96       return ENOENT;
97     }
98     memcpy(curPath, penv, (end - penv) * sizeof(_TCHAR));
99     if (curPath[end - penv] != '/' && curPath[end - penv] != '\\')
100     {
101       curPath[end - penv] = '\\';
102       curPath[end - penv + 1] = '\0';
103     }
104     else
105       curPath[end - penv] = '\0';
106 
107     _tcscat(curPath, file);
108     if (GetFileAttributes( curPath ) != INVALID_FILE_ATTRIBUTES)
109     {
110       if (_tcslen(curPath) + 1 > count)
111       {
112           MSVCRT_INVALID_PMT("buf[count] is too small", ERANGE);
113           return ERANGE;
114       }
115       _tcscpy(buf, curPath);
116       return 0;
117     }
118     penv = *end ? end + 1 : end;
119   } while(1);
120 
121 }
122