github.com/roboticscm/goman@v0.0.0-20210203095141-87c07b4a0a55/src/lib9/tempdir_unix.c (about)

     1  // Copyright 2013 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build darwin dragonfly freebsd linux netbsd openbsd solaris
     6  
     7  #include <u.h>
     8  #include <dirent.h>
     9  #include <sys/stat.h>
    10  #define NOPLAN9DEFINES
    11  #include <libc.h>
    12  
    13  char*
    14  mktempdir(void)
    15  {
    16  	char *tmp, *p;
    17  	
    18  	tmp = getenv("TMPDIR");
    19  	if(tmp == nil || strlen(tmp) == 0)
    20  		tmp = "/var/tmp";
    21  	p = smprint("%s/go-link-XXXXXX", tmp);
    22  	if(mkdtemp(p) == nil)
    23  		return nil;
    24  	return p;
    25  }
    26  
    27  void
    28  removeall(char *p)
    29  {
    30  	DIR *d;
    31  	struct dirent *dp;
    32  	char *q;
    33  	struct stat st;
    34  
    35  	if(stat(p, &st) < 0)
    36  		return;
    37  	if(!S_ISDIR(st.st_mode)) {
    38  		unlink(p);
    39  		return;
    40  	}
    41  
    42  	d = opendir(p);
    43  	while((dp = readdir(d)) != nil) {
    44  		if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
    45  			continue;
    46  		q = smprint("%s/%s", p, dp->d_name);
    47  		removeall(q);
    48  		free(q);
    49  	}
    50  	closedir(d);
    51  	rmdir(p);
    52  }