FileIO.cpp 15.8 KB
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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

#include "FileIO.h"
#include <string.h>
#include <assert.h>   
#include "DebugLog.h"
#include "dependencies.h"
   
#if defined(_LINUX_)
#include <unistd.h>
#include <ftw.h>   
#endif

#ifdef __BEOS__
#include <unistd.h>
#include <be/storage/Directory.h>
#endif
#include <stdlib.h>   

#ifdef WIN32
#include <shlobj.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
USING_NAMESPACE(CM);


#ifdef WIN32
#define F_OK 0
#define COPY_OK      0
#define COPY_ERROR  -1
#endif

#ifndef _MAXPATHLEN
#define _MAXPATHLEN 1024
#endif

// TODO Fix this function to take a const char * and return a const char *
// Possibility to take and return a String object
void NormalizeFileName(char *pathName)
{
  int i, j = 0;
  char copy[2048];
  strcpy(copy, pathName);
  int size = strlen(pathName);
  
  assert(size < 2040);
   
  for( i = 0; i < size; i++)
    {
#ifdef WIN32
      if(copy[i] == '\\'  && i < 2)
        {
          pathName[j++] = copy[i];
        } else
#endif
          if(copy[i] == '\\' || copy[i] == '/')
            {
              if (j > 0)
                {
                  if(pathName[j-1] != '/')
                    {
                      pathName[j++] = '/';      
                    }
                }
              else
                {
                  pathName[j++] = '/';      
                }
 
            }
          else
            {
              pathName[j++] = copy[i];
            }
    }
  pathName[j] = 0;

}

String GetFileName(String pathName)
{
  int32 idx = pathName.LastIndexOf('/',0);
//   if(idx == -1)
//     return "";
//   else
    return pathName.Substring(idx+1, pathName.Length());
}

String GetUserDir(void)
{
String userDir;

#ifdef WIN32
char dir[MAX_PATH];

  if (SHGetSpecialFolderPath( NULL, dir, CSIDL_PERSONAL, FALSE ) == TRUE)
  {
    userDir = dir;
  }
  else
  {
    //can't get user dir
    userDir = "";
  }
#endif // WIN32
   
#if defined (_LINUX_) || defined(__BEOS__)
  /* Under Linux, this directory path is the value of the environment variable 'HOME'. */ 
  userDir = getenv("HOME");
#endif // _LINUX_
  
  if (userDir == NULL)
    {
#ifdef WIN32   
      LOGERROR("Impossible to find your personal ('My Documents') directory.\n");
#endif
#if defined (_LINUX_) || defined (__BEOS__)   
      LOGERROR("Impossible to find your personal ('home') directory.\n");
#endif   
      my_exit(1); 
      return NULL; 
    }
  else
    {
      return userDir;
    }
}

String GetProgramRootDir(const char * argv)
{
  char argv0[1024];
  String execDir;
  String programName = argv0;
  char *evPATH;
  char *buf; 
  int i,j,k; 

  strncpy(argv0, argv, 1023);
	argv0[1023] = '\0';
#ifdef WIN32
  if(strncmp(argv0 + (strlen(argv) - 4) ,".exe",4) != 0 &&
     strncmp(argv0 + (strlen(argv) - 4) ,".EXE",4) != 0)
  {
    strcat(argv0,".exe");
  }
#endif
  if (argv0[0] == FILE_SEPARATOR
#ifdef WIN32
     || argv0[1] == ':'
#endif
    )
    {
      /* name of compiler is already an absolute path */ 
      i = 0; 
      while (argv0[i] != 0) i++; 
//      printf("I = %d\n", i);
      while (argv0[i] != FILE_SEPARATOR) i--;
      argv0[i] = 0; 
      execDir = argv0; 
      return execDir; 
    }
  else
    {
      #ifdef WIN32
      _getcwd(argv0, 1024);
      return argv0;
      #elif _LINUX_
      getcwd(argv0, 1024);
      return argv0;
      #endif
      /* name of compiler does not contain the complete path */ 
      if ((evPATH = getenv("PATH")) == NULL)
        {
          LOGERROR("Your 'PATH' shell variable is not defined.\n"); // will probably never happen
          my_exit(1); 
        }
   
      if ((buf = (char *)malloc(strlen(evPATH)+strlen(argv0)+10)) == NULL)
        {
          LOGERROR("Not enough memory.\n");
          my_exit(1);    
        }

      /* evPATH contains:
   
      "path_1:path_2:...:path_n"      or
      "path_1;path_2;...;path_n"
   
      */ 
   
      i = 0;  // marker for beginning of path
   
      while (evPATH[i] != 0)   // while there is still some path to check
        {
          if (evPATH[i] == ENV_PATH_SEPARATOR) { i++; } // avoid a possible leading ':'
          // copy path to buffer
          for (j = 0; evPATH[i+j] != ENV_PATH_SEPARATOR && evPATH[i+j] != 0; j++) { buf[j] = evPATH[i+j]; }
          // append "/name_of_program" (this may be either 'anubis' or 'anbexec')
          buf[j] = FILE_SEPARATOR;
          for (k = 0; argv0[k] != 0; k++) { buf[j+1+k] = argv0[k]; }
          // put a delimiting zero
          buf[j+1+k] = 0; 
          // check if the file "path/name_of_program" exists 
          if(FileExist(buf))  // our file is here
            {
              // replace the '/' just before 'name_of_program' by 0 (j did not change)
              buf[j] = 0;    
              //printf("Directory of executable is '%s'\n",buf); 
              execDir = buf; 
              free(buf);
              //printf("execDir = %s\n",execDir.Cstr()); 
              return execDir; 
            }
          // advance i
          i += j; 
        }
   
      LOGERROR("Unable to find directory of executable '%s'.\n",argv0); 
      my_exit(1); 
      return (String)NULL; 
    }
}

bool FileExist(String fileToCheck)
{
  if(access(fileToCheck.Cstr(),F_OK) == 0)
  {
    return true;
  }
  return false;
}


   
   
#ifdef _LINUX_
/* a little bit of (almost) functional programing in C */ 
   
/* The 'ftw' function calls the callback  'copy_create_item' on all files and directory of
   some initial directory, searching  into subdirectories. The callback 'copy_create_item'
   create a directory or copies a file. 
   
   The path  of the  source item  is provided  to the callback  by 'ftw'.  But there  is a
   problem with the destination directory. The initial destination is (for example):
   
       "/home/georges/my_anubis"     
   
   and the initial source is (for example):
    
       "/usr/local/anubis"
   
   during the process we may have to execute this:
   
   "cp /usr/local/anubis/library/examples/hello.anubis 
       /home/georges/my_anubis/library/examples/hello.anubis"
   
   The first argument of 'cp' is provided by  'ftw', but the second one is not. It must be
   computed. We just have to remove the initial source and add the initial destination:
   
     /usr/local/anubis/library/examples/hello.anubis
     /library/examples/hello.anubis
     /home/georges/my_anubis/library/examples/hello.anubis
   
   In the case of a directory, this gives:
   
     /usr/local/anubis/library/examples
     /library/examples
     /home/georges/my_anubis/library/examples
   
   Normally, the mkdir function will be  able to create the directory, because directories
   above this one will have been already  created. We need only to ensure that 'ftw' calls
   the callback for the directory before going into it.
   
   */ 
   
int initial_source_length = 0;     // length of initial source string
char *initial_destination = NULL;    
   
char *compute_destination(char *source)
{
  char *destination = (char *)malloc(strlen(initial_destination)+strlen(source)+1); 
  if (destination == NULL)
    {
      fprintf(stderr,"Not enough memory.\n"); 
      my_exit(1); 
    }
  sprintf(destination,"%s%s",initial_destination,source+initial_source_length); 
  return destination; 
}
   
int copy_create_item(const char *filename, const struct stat *s, int flag)
{
  char *dest = compute_destination((char *)filename); 
  
  switch(flag)
    {
    case FTW_F:    /* this is a file */ 
      {
        char *tmp = (char *)malloc(10+strlen(filename)+strlen(dest));
        sprintf(tmp,"cp %s %s",filename,dest); 
        //printf("executing: %s\n",tmp); 
        system(tmp);
        free(tmp); 
      }
      break; 
   
    case FTW_D:    /* this is a directory */ 
      mkdir(dest,S_IRWXU|S_IRWXG); 
      break; 
   
    default:
      break; 
    }
  free(dest); /* allocated by 'compute_destination' */ 
  return 0;  /* always succeeds */ 
}
      
   
bool RecursiveCopy(const String &srcDir, const String &destDir)
{
  initial_destination = (char *)destDir.Cstr(); 
  //printf("initial_destination = %s\n",initial_destination);
  initial_source_length = strlen(srcDir.Cstr());
  //printf("srcDir = %s\n",srcDir.Cstr()); 
  #ifdef LINUX
  ftw(srcDir.Cstr(),(__ftw_func_t)copy_create_item,10); 
  #else
  ftw(srcDir.Cstr(),copy_create_item,10); 
  #endif
  return 0; 
}
#endif
   
   
#ifdef WIN32
bool RecursiveCopy(const String &srcDir, const String &destDir)
{
  if(CM_CopyDir(srcDir, destDir, "*", true) == COPY_OK)
    return true;

  return false;
}
#endif

   
#ifdef WIN32   
int CM_CopyDir(const String& sourceDirPath, const String& destDirPath, const String &Filter, bool recursive)
{
  int ret = COPY_OK;
  
  int tmpret = CM_CopyFileDir(sourceDirPath, destDirPath, Filter);
  if(tmpret != COPY_OK)
      ret = tmpret;
   
  if (recursive)
  {
    String OrigDir = sourceDirPath + "\\" + Filter;
    String DestDir;
    WIN32_FIND_DATA Data;
    HANDLE FileHandle = FindFirstFile(OrigDir.Cstr(), &Data);
    BOOL Continue = TRUE;
    while (FileHandle != INVALID_HANDLE_VALUE && Continue)
    {
      String lSourceFileName = sourceDirPath + "\\" + Data.cFileName;
      String lDestDir     = destDirPath + "\\" + Data.cFileName;
      // Cas d'un r�ertoire
      if ((Data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (Data.cFileName[0] != '.'))
      {
        // On rentre dans le r�ertoire 
        ret = CM_CopyDir(lSourceFileName, lDestDir, Filter, recursive);
        if(ret != COPY_OK)
          return ret;
        Continue  = FindNextFile(FileHandle, &Data);
      }
      else
        Continue = FindNextFile(FileHandle, &Data);
    }
    FindClose(FileHandle);
  }
  return ret;
}
#endif
   
#ifdef WIN32   
int CM_CopyFileDir(const String &sourceDirPath, const String &destDirPath, const String &filter)
{
  int ret = COPY_OK;
  int retry = 0;
  
  String OrigDir = sourceDirPath + "\\" + filter;
  String DestDir;
  WIN32_FIND_DATA Data;
  HANDLE FileHandle = FindFirstFile(OrigDir.Cstr(), &Data);
  BOOL Continue = TRUE;
  CreateAllDirectories(destDirPath.Cstr(), false);

  while (FileHandle != INVALID_HANDLE_VALUE && Continue)
  {

      // Cas d'un r�ertoire
      if ((Data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (Data.cFileName[0] != '.'))
      {
        Continue = FindNextFile(FileHandle, &Data);
      }
      // Cas d'un fichier
      else if(Data.cFileName[0] != '.')
      {
        String lSourceFileName = sourceDirPath + "\\" + Data.cFileName;
        String lDestFileName   = destDirPath + "\\" + Data.cFileName;
        retry = 0;

        do 
        {
          ret = CM_CopyFile(lSourceFileName, lDestFileName);

          if(ret != COPY_OK)
          {
            if(retry == 3)
            {
//              tmpStr.Printf("COPY FILE ERROR too many retry of \n %s\n",lDestFileName.Cstr());
//              outString.PrintError(tmpStr);
              return ret;
            }
            else
              retry++;
          }

        } while(ret != COPY_OK);

        Continue = FindNextFile(FileHandle, &Data);
      }
      else
        Continue = FindNextFile(FileHandle, &Data);
  }
  FindClose(FileHandle);

  
  return ret;
}
#endif
   
   
#ifdef WIN32   
int CM_CopyFile(const String& srcFile, const String& desFile)
{
#define BUFFER_SIZE 65536

int32 readByte;
//bool      mustDoSha1 = false;
int   ret = COPY_OK;
String hashKey = "";


	char* buff = new char[BUFFER_SIZE];

	FILE * fdr = fopen(srcFile.Cstr(), "rb");
  if(!fdr)
    return COPY_ERROR;

  FILE * fdw = fopen(desFile.Cstr(), "wb");
  if(!fdw)
  {
    fclose(fdr);
    return COPY_ERROR;
  }


  struct stat srcFileStat;
  //Get stat of file 
  stat(srcFile.Cstr(), &srcFileStat);
  DWORD fAttribut = GetFileAttributes(srcFile.Cstr());
  fAttribut &= ~FILE_ATTRIBUTE_READONLY;
	while((readByte = fread(buff, 1, BUFFER_SIZE, fdr)) > 0)
	{

		if(ret != COPY_OK)
		{
			fclose(fdr);
      fclose(fdw);
			SAFE_DELETE_TAB(buff);
			return ret;
		}
      
    fwrite(buff,1, readByte, fdw);
	}

  CM_SetAllTime(fdr, fdw);
  SetFileAttributes(desFile.Cstr(), fAttribut);
  
	SAFE_DELETE_TAB(buff);

	fclose(fdr);
  fclose(fdw);
  
	return ret;
}
#endif
   
   
#ifdef WIN32   
void CM_SetAllTime(FILE* srcFile, FILE* dstFile)
{
  HANDLE hSrcFile = (void*)_get_osfhandle(((FILE*)srcFile)->_file);
  HANDLE hDstFile = (void*)_get_osfhandle(((FILE*)dstFile)->_file);
  FILETIME creationTime;
  FILETIME modificationTime;
  FILETIME accessTime;

  GetFileTime(hSrcFile,&creationTime, &accessTime, &modificationTime);
  SetFileTime(hDstFile,&creationTime, &accessTime, &modificationTime);
  
}
#endif
   
   

int CreateAllDirectories(const char*   directory, bool haveFile )
{
#ifdef __BEOS__
	return create_directory(directory, 0777);
#endif   
   
#ifdef _LINUX_
        return 0; 
#endif   
   
#ifdef WIN32
  char*   pszLastSlash;
  char    cTmp;
	
	char dir[1024];

	size_t len  = strlen(directory);
	memcpy(dir, directory, len+1);

	NormalizeFileName(dir);

  if(haveFile)
  {
    pszLastSlash = strrchr( dir, FILE_SEPARATOR );
    if ( pszLastSlash )
    {
      *pszLastSlash = '\0';
//      strcpy(dir, pszLastSlash);
    }
    haveFile = false;
  }

	if( access( dir, 0 ) != -1 )
	{
		//Existe deja
		return 0;
	}

	pszLastSlash = strrchr( dir, FILE_SEPARATOR );
	if ( pszLastSlash )
	{
		cTmp = *pszLastSlash;
		*pszLastSlash = '\0';
		
		// Ressaye avec un niveau en moins
		CreateAllDirectories( dir , haveFile);
		*pszLastSlash = cTmp;
	}

	int res = mkdir( dir ); 
	if ( res == -1 )
	{
		if( access( dir, 0 ) != -1 )
			return 0;
		return -1;
	}

return 0;
#endif
}

#ifdef WIN32
void CM_TimetToFileTime( time_t t, LPFILETIME pft )
{
		FILETIME fileTime;
    LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
    fileTime.dwLowDateTime = (DWORD) ll;
    fileTime.dwHighDateTime = (DWORD)(ll >>32);
		// Conversion de t (exprim�en UTC) en local time pour usage avec SetFileTime()
//		FileTimeToLocalFileTime(&fileTime, pft);
		*pft = fileTime;
}

void CM_FileTimeToTime( time_t& t, LPFILETIME pft )
{
	FILETIME fileTime = *pft;
//	FileTimeToLocalFileTime(pft, &fileTime);
  int64 ll = ((int64)fileTime.dwHighDateTime << 32) | (int64)fileTime.dwLowDateTime;
	ll = (ll - 116444736000000000) / 10000000 ;
	t = (time_t)ll;
}

bool CM_SetModificationTime(const char * file_name, const time_t aModificationTime)
{
  FILETIME modificationTime;
  memset(&modificationTime, 0, sizeof(modificationTime));

	CM_TimetToFileTime(aModificationTime, &modificationTime);

  NormalizeFileName((char*)file_name);
	HANDLE hFile = CreateFile(file_name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

  BOOL result = ::SetFileTime(hFile, 0, 0, &modificationTime);

  /* if (result == false)
  {
    int err = GetLastError();
  } */

  CloseHandle(hFile);
  return result ? true : false;
}

bool CM_SetAccessTime(const char *file_name, const time_t aAccessTime)
{
  FILETIME accessTime;
  memset(&accessTime, 0, sizeof(accessTime));

	CM_TimetToFileTime(aAccessTime, &accessTime);
  NormalizeFileName((char*)file_name);
  
	HANDLE hFile = CreateFile(file_name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

  BOOL result = ::SetFileTime(hFile, 0, &accessTime, 0);

  /*if (result == false)
  {
    int err = GetLastError();
  }*/
  
  CloseHandle(hFile);
  return result ? true : false;
}

#endif


// Get current working directory.
// If buf is NULL, allocates space using new, else
// copies into buf.
char *GetWorkingDirectory(char *buf, int sz)
{
#ifdef WINCE
	return NULL;
#else
	if ( !buf )
	{
		buf = new char[sz + 1];
	}
	
	bool ok = false;
	
	
#ifdef WIN32
	ok = _getcwd(buf, sz) != NULL;
#else // !Win32/VC++ !Mac !OS2
	ok = getcwd(buf, sz) != NULL;
#endif // platform
	
	if ( !ok )
	{
		LOGERROR("Failed to get the working directory");
		
		buf[0] = '\0';
	}
	
	return buf;
#endif	//!def WINCE
}

//////////////////////////////////////////////////////////////////////////

String GetCwd()
{
	char *buffer = new char[_MAXPATHLEN];
	GetWorkingDirectory(buffer, _MAXPATHLEN);
	String str( buffer );
	delete [] buffer;
	
	return str;
}