Commit | Line | Data |
---|---|---|
d9ebc974 AW |
1 | /* mbed Microcontroller Library - FATFileHandle |
2 | * Copyright (c) 2008, sford | |
3 | */ | |
4 | ||
5 | #include "FATFileHandle.h" | |
6 | ||
7 | #include <stdio.h> | |
8 | #include <stdlib.h> | |
9 | #include "ff.h" | |
10 | #include "FATFileSystem.h" | |
11 | ||
12 | namespace mbed { | |
13 | ||
14 | #if FFSDEBUG_ENABLED | |
15 | static const char *FR_ERRORS[] = { | |
df27a6a3 MM |
16 | "FR_OK = 0", |
17 | "FR_NOT_READY", | |
18 | "FR_NO_FILE", | |
19 | "FR_NO_PATH", | |
20 | "FR_INVALID_NAME", | |
21 | "FR_INVALID_DRIVE", | |
22 | "FR_DENIED", | |
23 | "FR_EXIST", | |
24 | "FR_RW_ERROR", | |
25 | "FR_WRITE_PROTECTED", | |
26 | "FR_NOT_ENABLED", | |
27 | "FR_NO_FILESYSTEM", | |
28 | "FR_INVALID_OBJECT", | |
29 | "FR_MKFS_ABORTED" | |
d9ebc974 AW |
30 | }; |
31 | #endif | |
32 | ||
df27a6a3 | 33 | FATFileHandle::FATFileHandle(FIL_t fh) { |
d9ebc974 AW |
34 | _fh = fh; |
35 | } | |
36 | ||
37 | int FATFileHandle::close() { | |
38 | FFSDEBUG("close\n"); | |
39 | int retval = f_close(&_fh); | |
40 | delete this; | |
41 | return retval; | |
42 | } | |
43 | ||
44 | ssize_t FATFileHandle::write(const void* buffer, size_t length) { | |
45 | FFSDEBUG("write(%d)\n", length); | |
46 | UINT n; | |
47 | FRESULT res = f_write(&_fh, buffer, length, &n); | |
df27a6a3 | 48 | if(res) { |
d9ebc974 AW |
49 | FFSDEBUG("f_write() failed (%d, %s)", res, FR_ERRORS[res]); |
50 | return -1; | |
51 | } | |
52 | return n; | |
53 | } | |
54 | ||
55 | ssize_t FATFileHandle::read(void* buffer, size_t length) { | |
56 | FFSDEBUG("read(%d)\n", length); | |
57 | UINT n; | |
58 | FRESULT res = f_read(&_fh, buffer, length, &n); | |
59 | if(res) { | |
60 | FFSDEBUG("f_read() failed (%d, %s)\n", res, FR_ERRORS[res]); | |
61 | return -1; | |
62 | } | |
63 | return n; | |
64 | } | |
65 | ||
66 | int FATFileHandle::isatty() { | |
67 | return 0; | |
68 | } | |
69 | ||
70 | off_t FATFileHandle::lseek(off_t position, int whence) { | |
71 | FFSDEBUG("lseek(%i,%i)\n",position,whence); | |
72 | if(whence == SEEK_END) { | |
73 | position += _fh.fsize; | |
74 | } else if(whence==SEEK_CUR) { | |
75 | position += _fh.fptr; | |
76 | } | |
77 | FRESULT res = f_lseek(&_fh, position); | |
78 | if(res) { | |
79 | FFSDEBUG("lseek failed (%d, %s)\n", res, FR_ERRORS[res]); | |
80 | return -1; | |
81 | } else { | |
82 | FFSDEBUG("lseek OK, returning %i\n", _fh.fptr); | |
83 | return _fh.fptr; | |
84 | } | |
85 | } | |
86 | ||
87 | int FATFileHandle::fsync() { | |
88 | FFSDEBUG("fsync()\n"); | |
89 | FRESULT res = f_sync(&_fh); | |
90 | if (res) { | |
91 | FFSDEBUG("f_sync() failed (%d, %s)\n", res, FR_ERRORS[res]); | |
92 | return -1; | |
93 | } | |
94 | return 0; | |
95 | } | |
96 | ||
97 | off_t FATFileHandle::flen() { | |
98 | FFSDEBUG("flen\n"); | |
99 | return _fh.fsize; | |
100 | } | |
101 | ||
102 | } // namespace mbed |