-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGetPathDir.c
64 lines (57 loc) · 2.5 KB
/
GetPathDir.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* Get Base Path of a file
* Copyright (C) 2007-2016 Mathieu CARBONNEAUX
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "GetPathDir.h"
// Retrieves the pathpath from a pathname.
//
// Returns: MCA_SUCCESS if the basepath is present and successfully copied to the p_base_path buffer
// MCA_FAILURE_NULL_ARGUMENT if any arguments are NULL
// MCA_FAILURE_INVALID_ARGUMENTS if either buffer size is less than 1
// MCA_FAILURE_BUFFER_TOO_SMALL if the p_basepath buffer is too small
// MCA_FAILURE_INVALID_PATH if the p_pathname doesn't have a path (e.g. C:, calc.exe, ?qwa)
// MCA_FAILURE_API_CALL if there is an error from the underlying API calls
int get_base_path_from_pathname( const char* const p_pathname,
size_t pathname_size,
char* const p_basepath,
size_t basepath_size )
{
char* p_end_of_path;
size_t path_length;
int return_code;
// Parameter Validation
if( p_pathname == NULL || p_basepath == NULL ) { return MCA_FAILURE_NULL_ARGUMENT; }
if( pathname_size < 1 || basepath_size < 1 ) { return MCA_FAILURE_INVALID_ARGUMENTS; }
// Returns a pointer to the last occurrence of \ in p_pathname or NULL if it is not found
p_end_of_path = strrchr( p_pathname, '/' );
if( p_end_of_path == NULL )
{
// There is no path part
return MCA_FAILURE_INVALID_PATH;
}
else
{
path_length = (size_t)( p_end_of_path - p_pathname + 1 );
// Do some sanity checks on the length
if( path_length < 1 ) { return MCA_FAILURE_INVALID_PATH; }
if( ( path_length + 1 ) > basepath_size ) { return MCA_FAILURE_BUFFER_TOO_SMALL; }
// Copy the base path into the out variable
strncpy(p_basepath, p_pathname, path_length);
p_basepath[path_length] = '\0';
}
return MCA_SUCCESS;
}