inlib
1.2.0
|
00001 // Copyright (C) 2010, Guy Barrand. All rights reserved. 00002 // See the file inlib.license for terms. 00003 00004 #ifndef inlib_sys_file 00005 #define inlib_sys_file 00006 00007 #include <string> 00008 #include <cstdlib> 00009 #include <cstdio> 00010 #include <sstream> 00011 00012 #include <sys/stat.h> 00013 00014 #ifdef WIN32 00015 #include <process.h> 00016 #else 00017 #include <unistd.h> 00018 #endif 00019 00020 namespace inlib { 00021 00022 inline bool tmpname(const std::string& a_dir,const std::string& a_prefix,const std::string& a_suffix,std::string& a_name){ 00023 // a_dir must finish with the system path separator. 00024 std::string head; 00025 if(a_dir==".") { 00026 } else if(a_dir.size()) { 00027 head += a_dir; 00028 } else { 00029 #ifdef WIN32 00030 char* env = ::getenv("HOMEDRIVE"); 00031 std::string drive = (env? env : std::string("C:")); 00032 head += drive; 00033 head += "\\"; 00034 #else 00035 head += "/tmp/"; 00036 #endif 00037 } 00038 head += a_prefix; 00039 char spid[128]; 00040 #ifdef WIN32 00041 _snprintf(spid,sizeof(spid),"%d",::getpid()); 00042 #else 00043 ::snprintf(spid,sizeof(spid),"%d",::getpid()); 00044 #endif 00045 head += spid; 00046 head += "_"; 00047 00048 for(int count=0;count<1000;count++) { 00049 //std::ostringstream strm; //because of Android which has no STL. 00050 //strm.fill('0'); 00051 //strm.width(3); 00052 //strm << count; 00053 char s[32]; 00054 #ifdef WIN32 00055 _snprintf(s,sizeof(s),"%03d",count); 00056 #else 00057 ::snprintf(s,sizeof(s),"%03d",count); 00058 #endif 00059 std::string tmpnm = head; 00060 tmpnm += s; 00061 //tmpnm += strm.str(); 00062 tmpnm += a_suffix; 00063 struct stat finfo; 00064 if(::stat(tmpnm.c_str(),&finfo) < 0) { 00065 // No directory or file found : 00066 a_name = tmpnm; // Good file name. 00067 return true; 00068 } 00069 } 00070 // No good name found : 00071 a_name.clear(); 00072 return false; 00073 } 00074 00075 } 00076 00077 #endif