2 * ========================================================================
3 * Copyright 2006-2007 University of Washington
4 * Copyright 2013-2022 Eduardo Chappa
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * ========================================================================
15 #include "../pith/headers.h"
16 #include "../pith/tempfile.h"
20 * Return the name of a file in the same directory as filename.
21 * Same as temp_nam except it figures out a name in the same directory.
22 * It also returns the name of the directory in ret_dir if ret_dir is
23 * not NULL. That has to be freed by caller. If return is not NULL the
24 * empty file has been created.
27 tempfile_in_same_dir(char *filename
, char *prefix
, char **ret_dir
)
30 #define MAXPATH 1000 /* Longest file path we can deal with */
34 char *ret_file
= NULL
;
39 if((lc
= last_cmpnt(filename
)) != NULL
){
42 to_copy
= (lc
- filename
> 1) ? (lc
- filename
- 1) : 1;
43 strncpy(dir
, filename
, MIN(to_copy
, sizeof(dir
)-1));
44 dir
[MIN(to_copy
, sizeof(dir
)-1)] = '\0';
55 /* temp_nam creates ret_file */
56 ret_file
= temp_nam(dirp
, prefix
);
59 * If temp_nam can't write in dirp it puts the file in a temp directory
60 * anyway. We don't want that to happen to us.
62 if(dirp
&& ret_file
&& !in_dir(dirp
, ret_file
)){
64 fs_give((void **)&ret_file
); /* sets it to NULL */
67 if(ret_file
&& ret_dir
&& dirp
)
68 *ret_dir
= cpystr(dirp
);
76 * Returns non-zero if dir is a prefix of path.
77 * zero if dir is not a prefix of path, or if dir is empty.
80 in_dir(char *dir
, char *path
)
82 return(*dir
? !strncmp(dir
, path
, strlen(dir
)) : 0);