Utility for copying and renaming files.
Utility for copying and renaming files.
FileUtils.h@2:361360b2f1c5, 2015-01-26 (annotated)
- Committer:
- ollie8
- Date:
- Mon Jan 26 08:28:04 2015 +0000
- Revision:
- 2:361360b2f1c5
- Parent:
- 1:1f1e0c92b3f8
Fixed bug where rename would always return true.
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
ollie8 | 0:4be393eec2a2 | 1 | |
ollie8 | 2:361360b2f1c5 | 2 | #define DEBUG |
ollie8 | 2:361360b2f1c5 | 3 | #include "logger.h" |
ollie8 | 0:4be393eec2a2 | 4 | /** fcopy: Copies a file |
ollie8 | 2:361360b2f1c5 | 5 | * Checks to ensure destination file was created. |
ollie8 | 0:4be393eec2a2 | 6 | * Returns -1 = error; 0 = success |
ollie8 | 0:4be393eec2a2 | 7 | */ |
ollie8 | 0:4be393eec2a2 | 8 | int fcopy (const char *src, const char *dst) { |
ollie8 | 0:4be393eec2a2 | 9 | FILE *fpsrc = fopen(src, "r"); |
ollie8 | 0:4be393eec2a2 | 10 | FILE *fpdst = fopen(dst, "w"); |
ollie8 | 0:4be393eec2a2 | 11 | int ch = fgetc(fpsrc); |
ollie8 | 0:4be393eec2a2 | 12 | while (ch != EOF) { |
ollie8 | 0:4be393eec2a2 | 13 | fputc(ch, fpdst); |
ollie8 | 0:4be393eec2a2 | 14 | ch = fgetc(fpsrc); |
ollie8 | 0:4be393eec2a2 | 15 | } |
ollie8 | 0:4be393eec2a2 | 16 | fclose(fpsrc); |
ollie8 | 1:1f1e0c92b3f8 | 17 | fclose(fpdst); |
ollie8 | 0:4be393eec2a2 | 18 | int retval = 0; |
ollie8 | 0:4be393eec2a2 | 19 | fpdst = fopen(dst, "r"); |
ollie8 | 0:4be393eec2a2 | 20 | if (fpdst == NULL) { |
ollie8 | 2:361360b2f1c5 | 21 | retval = 0; |
ollie8 | 0:4be393eec2a2 | 22 | } else { |
ollie8 | 0:4be393eec2a2 | 23 | fclose(fpdst); |
ollie8 | 2:361360b2f1c5 | 24 | retval = 1; |
ollie8 | 0:4be393eec2a2 | 25 | } |
ollie8 | 0:4be393eec2a2 | 26 | return retval; |
ollie8 | 0:4be393eec2a2 | 27 | } |
ollie8 | 0:4be393eec2a2 | 28 | |
ollie8 | 0:4be393eec2a2 | 29 | /** frename: renames a file (via copy & delete). |
ollie8 | 0:4be393eec2a2 | 30 | * Moves data instead of adjusting the file name in the |
ollie8 | 2:361360b2f1c5 | 31 | * file directory. Checks to ensure the file was renamed. |
ollie8 | 0:4be393eec2a2 | 32 | * Returns -1 = error; 0 = success |
ollie8 | 0:4be393eec2a2 | 33 | */ |
ollie8 | 0:4be393eec2a2 | 34 | int frename(const char *oldfname, const char *newfname) { |
ollie8 | 2:361360b2f1c5 | 35 | int retval = -1; |
ollie8 | 2:361360b2f1c5 | 36 | INFO("Renaming"); |
ollie8 | 0:4be393eec2a2 | 37 | if (fcopy(oldfname, newfname)) { |
ollie8 | 2:361360b2f1c5 | 38 | INFO("Deleting"); |
ollie8 | 0:4be393eec2a2 | 39 | remove(oldfname); |
ollie8 | 2:361360b2f1c5 | 40 | retval = 0; |
ollie8 | 0:4be393eec2a2 | 41 | } |
ollie8 | 2:361360b2f1c5 | 42 | INFO("Done"); |
ollie8 | 0:4be393eec2a2 | 43 | return retval; |
ollie8 | 0:4be393eec2a2 | 44 | } |