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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
|
/*
* util.cpp - miscellaneous support functions.
*
* Copyright (c) 2004 by Alastair M. Robinson
* Distributed under the terms of the GNU General Public License -
* see the file named "COPYING" for more details.
*
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include "support/searchpath.h"
#include "support/pathsupport.h"
using namespace std;
bool CheckSettingsDir(const char *dirname)
{
// const char *homedir=getenv("HOME");
const char *homedir=get_homedir();
if(homedir)
{
char *path=(char *)malloc(strlen(homedir)+strlen(dirname)+2);
sprintf(path,"%s%c%s",homedir,SEARCHPATH_SEPARATOR,dirname);
cerr << "Settings directory: " << path << endl;
struct stat s;
if(stat(path,&s)!=0)
{
cerr << "Need to create directory... " << errno << endl;
if(errno==ENOENT)
#ifdef WIN32
mkdir(path);
#else
mkdir(path,0755);
#endif
}
free(path);
return(true);
}
else
return(false);
}
char *BuildAbsoluteFilename(const char *fname)
{
char *result=NULL;
char cwdbuf[1024];
int l;
getcwd(cwdbuf,1023);
l=strlen(fname)+strlen(cwdbuf)+3;
result=(char *)malloc(l);
sprintf(result,"%s%c%s",cwdbuf,SEARCHPATH_SEPARATOR,fname);
return(result);
}
char *SerialiseFilename(const char *fname,int serialno,int max)
{
int digits=0;
while(max)
{
++digits;
max/=10;
}
char *ftmp=strdup(fname);
char *extension="";
int idx=strlen(ftmp)-1;
while(idx>0)
{
if(ftmp[idx]=='.')
break;
--idx;
}
if(idx)
{
extension=ftmp+idx+1;
ftmp[idx]=0;
}
char *result=(char *)malloc(strlen(ftmp)+strlen(extension)+digits+4);
if(digits)
sprintf(result,"%s_%0*d.%s",ftmp,digits,serialno,extension);
else
sprintf(result,"%s_%d.%s",ftmp,serialno,extension);
free(ftmp);
return(result);
}
int TestNumeric(char *str)
{
int result=1;
int c;
while((c=*str++))
{
if((c<'0')||(c>'9'))
result=0;
}
return(result);
}
int TestHostName(char *str,char **hostname,int *port)
{
int result=0;
int c;
char *src=str;
while((c=*src++))
{
if(c==':')
{
if(TestNumeric(src))
{
int hnl=src-str;
*port=atoi(src);
*hostname=(char *)malloc(hnl+1);
strncpy(*hostname,str,hnl);
(*hostname)[hnl-1]=0;
result=1;
}
}
}
return(result);
}
|