----------------------------------------------------------------------------- Open a file in the mode specified by openMode (Read, Write, or ReadWrite). Truncate the file if the mode is either Write or ReadWrite and truncate is true. Sets capability appropriate to the openMode. Returns the currentStatus of the file. -----------------------------------------------------------------------------
| 460 | // Returns the currentStatus of the file. |
| 461 | //----------------------------------------------------------------------------- |
| 462 | File::Status File::open(const char *filename, const AccessMode openMode) |
| 463 | { |
| 464 | AssertFatal(NULL != filename, "File::open: NULL filename"); |
| 465 | AssertWarn(NULL == handle, "File::open: handle already valid"); |
| 466 | |
| 467 | // Close the file if it was already open... |
| 468 | if (Closed != currentStatus) |
| 469 | close(); |
| 470 | |
| 471 | char prefPathName[MaxPath]; |
| 472 | char gamePathName[MaxPath]; |
| 473 | char cwd[MaxPath]; |
| 474 | getcwd(cwd, MaxPath); |
| 475 | MungePath(prefPathName, MaxPath, filename, GetPrefDir()); |
| 476 | MungePath(gamePathName, MaxPath, filename, cwd); |
| 477 | |
| 478 | int oflag; |
| 479 | struct stat filestat; |
| 480 | handle = (void *)dRealMalloc(sizeof(int)); |
| 481 | |
| 482 | switch (openMode) |
| 483 | { |
| 484 | case Read: |
| 485 | oflag = O_RDONLY; |
| 486 | break; |
| 487 | case Write: |
| 488 | oflag = O_WRONLY | O_CREAT | O_TRUNC; |
| 489 | break; |
| 490 | case ReadWrite: |
| 491 | oflag = O_RDWR | O_CREAT; |
| 492 | // if the file does not exist copy it before reading/writing |
| 493 | if (stat(prefPathName, &filestat) == -1) |
| 494 | bool ret = CopyFile(gamePathName, prefPathName); |
| 495 | break; |
| 496 | case WriteAppend: |
| 497 | oflag = O_WRONLY | O_CREAT | O_APPEND; |
| 498 | // if the file does not exist copy it before appending |
| 499 | if (stat(prefPathName, &filestat) == -1) |
| 500 | bool ret = CopyFile(gamePathName, prefPathName); |
| 501 | break; |
| 502 | default: |
| 503 | AssertFatal(false, "File::open: bad access mode"); // impossible |
| 504 | } |
| 505 | |
| 506 | // if we are writing, make sure output path exists |
| 507 | if (openMode == Write || openMode == ReadWrite || openMode == WriteAppend) |
| 508 | Platform::createPath(prefPathName); |
| 509 | |
| 510 | int fd = -1; |
| 511 | fd = x86UNIXOpen(prefPathName, oflag); |
| 512 | if (fd == -1 && openMode == Read) |
| 513 | // for read only files we can use the gamePathName |
| 514 | fd = x86UNIXOpen(gamePathName, oflag); |
| 515 | |
| 516 | dMemcpy(handle, &fd, sizeof(int)); |
| 517 | |
| 518 | #ifdef DEBUG |
| 519 | // fprintf(stdout,"fd = %d, handle = %d\n", fd, *((int *)handle)); |
no test coverage detected