| 35 | bool SaveFileManager::renameSavefile(const char *oldFilename, const char *newFilename) { |
| 36 | |
| 37 | enum { |
| 38 | NOTHING_DONE = 0, |
| 39 | OPEN_LOAD = 1, |
| 40 | OPEN_SAVE = 2, |
| 41 | BUFFER_READY = 4, // for flexibility: we may want not to assert as we do when failing to allocate the buffer |
| 42 | COPIED = 8, |
| 43 | CAN_COPY = OPEN_SAVE | BUFFER_READY, |
| 44 | }; |
| 45 | |
| 46 | uint32 status = NOTHING_DONE; |
| 47 | InSaveFile *inFile = 0; |
| 48 | OutSaveFile *outFile = 0; |
| 49 | uint32 size = 0; |
| 50 | void *buffer = 0; |
| 51 | bool success = false; |
| 52 | |
| 53 | inFile = openForLoading(oldFilename); |
| 54 | status |= (inFile) ? OPEN_LOAD : NOTHING_DONE; |
| 55 | |
| 56 | if (status & OPEN_LOAD) { |
| 57 | size = inFile->size(); |
| 58 | buffer = malloc(size); |
| 59 | assert(buffer); |
| 60 | status |= BUFFER_READY; |
| 61 | |
| 62 | outFile = openForSaving(newFilename); |
| 63 | status |= (outFile) ? OPEN_SAVE : NOTHING_DONE; |
| 64 | |
| 65 | if (status & CAN_COPY) { |
| 66 | inFile->read(buffer, size); |
| 67 | if (!inFile->ioFailed()) { |
| 68 | outFile->write(buffer, size); |
| 69 | status |= (outFile->ioFailed()) ? NOTHING_DONE : COPIED; |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | if (status & BUFFER_READY) { |
| 75 | free(buffer); |
| 76 | } |
| 77 | |
| 78 | if (status & OPEN_SAVE) { |
| 79 | outFile->finalize(); |
| 80 | delete outFile; |
| 81 | } |
| 82 | |
| 83 | if (status & OPEN_LOAD) { |
| 84 | delete inFile; |
| 85 | } |
| 86 | |
| 87 | if (status & COPIED) { |
| 88 | success = removeSavefile(oldFilename); |
| 89 | } |
| 90 | |
| 91 | return success; |
| 92 | } |
| 93 | |