Subversion Repositories Projects

Rev

Rev 318 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 318 Rev 333
1
#include <string.h>
1
#include <string.h>
2
#include "printf_P.h"
2
#include "printf_P.h"
3
#include "timer0.h"
3
#include "timer0.h"
4
#include "fat16.h"
4
#include "fat16.h"
5
#include "sdc.h"
5
#include "sdc.h"
6
#include "uart1.h"
6
#include "uart1.h"
7
 
7
 
8
 
8
 
9
/*
9
/*
10
FAT16 Drive Layout:
10
FAT16 Drive Layout:
11
Description                                             Offset
11
Description                                             Offset
12
Volume Boot Sector                                      Start of Partition
12
Volume Boot Sector                                      Start of Partition
13
Fat Tables                                                      Start + # of Reserved Sectors
13
Fat Tables                                                      Start + # of Reserved Sectors
14
Root Directory Entry                            Start + # of Reserved + (# of Sectors Per FAT * 2)
14
Root Directory Entry                            Start + # of Reserved + (# of Sectors Per FAT * 2)
15
Data Area (Starts with Cluster #2)      Start + # of Reserved + (# of Sectors Per FAT * 2) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
15
Data Area (Starts with Cluster #2)      Start + # of Reserved + (# of Sectors Per FAT * 2) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
16
*/
16
*/
17
 
17
 
18
 
18
 
19
/*
19
/*
20
________________________________________________________________________________________________________________________________________
20
________________________________________________________________________________________________________________________________________
21
 
21
 
22
        Structure of an partition entry
22
        Structure of an partition entry
23
________________________________________________________________________________________________________________________________________
23
________________________________________________________________________________________________________________________________________
24
 
24
 
25
        Partition Entry is 16 bytes long
25
        Partition Entry is 16 bytes long
26
*/
26
*/
27
typedef struct
27
typedef struct
28
{
28
{
29
        uint8_t         PartitionState;                         // Current State of Partition (00h=Inactive, 80h=Active)
29
        uint8_t         PartitionState;                         // Current State of Partition (00h=Inactive, 80h=Active)
30
        uint8_t         BeginningHead;                          // Beginning of Partition - Head
30
        uint8_t         BeginningHead;                          // Beginning of Partition - Head
31
        uint16_t        BeginningCylSec;                        // Beginning of Partition - Cylinder/Sector (See Below)
31
        uint16_t        BeginningCylSec;                        // Beginning of Partition - Cylinder/Sector (See Below)
32
        uint8_t         Type;                                           // Type of Partition (See List Below)
32
        uint8_t         Type;                                           // Type of Partition (See List Below)
33
        uint8_t         EndHead;                                        // End of Partition - Head
33
        uint8_t         EndHead;                                        // End of Partition - Head
34
        uint16_t        EndCylSec;                                      // End of Partition - Cylinder/Sector
34
        uint16_t        EndCylSec;                                      // End of Partition - Cylinder/Sector
35
        uint32_t        NoSectorsBeforePartition;       // Number of Sectors between the MBR and the First Sector in the Partition
35
        uint32_t        NoSectorsBeforePartition;       // Number of Sectors between the MBR and the First Sector in the Partition
36
        uint32_t        NoSectorsPartition      ;               // Number of Sectors in the Partition
36
        uint32_t        NoSectorsPartition      ;               // Number of Sectors in the Partition
37
} __attribute__((packed)) PartitionEntry_t;
37
} __attribute__((packed)) PartitionEntry_t;
38
 
38
 
39
/*
39
/*
40
Coding of Cylinder/Sector words
40
Coding of Cylinder/Sector words
41
 
41
 
42
Cylinder is 10 bits:  [7:0] at [15:8] and [9:8] at [7:6]
42
Cylinder is 10 bits:  [7:0] at [15:8] and [9:8] at [7:6]
43
Sector is 5 bits:  [5:0] at [5:0]
43
Sector is 5 bits:  [5:0] at [5:0]
44
*/
44
*/
45
 
45
 
46
// Partition Types:
46
// Partition Types:
47
#define PART_TYPE_UNKNOWN                       0x00
47
#define PART_TYPE_UNKNOWN                       0x00
48
#define PART_TYPE_FAT12                         0x01
48
#define PART_TYPE_FAT12                         0x01
49
#define PART_TYPE_XENIX                         0x02
49
#define PART_TYPE_XENIX                         0x02
50
#define PART_TYPE_FAT16_ST_32_MB        0x04
50
#define PART_TYPE_FAT16_ST_32_MB        0x04
51
#define PART_TYPE_EXTDOS                        0x05
51
#define PART_TYPE_EXTDOS                        0x05
52
#define PART_TYPE_FAT16_LT_32_MB        0x06
52
#define PART_TYPE_FAT16_LT_32_MB        0x06
53
#define PART_TYPE_NTFS                          0x07
53
#define PART_TYPE_NTFS                          0x07
54
#define PART_TYPE_FAT32                         0x0B
54
#define PART_TYPE_FAT32                         0x0B
55
#define PART_TYPE_FAT32LBA                      0x0C
55
#define PART_TYPE_FAT32LBA                      0x0C
56
#define PART_TYPE_FAT16LBA                      0x0E
56
#define PART_TYPE_FAT16LBA                      0x0E
57
#define PART_TYPE_EXTDOSLBA                     0x0F
57
#define PART_TYPE_EXTDOSLBA                     0x0F
58
#define PART_TYPE_EISA                          0x12
58
#define PART_TYPE_EISA                          0x12
59
#define PART_TYPE_ONTRACK                       0x33
59
#define PART_TYPE_ONTRACK                       0x33
60
#define PART_TYPE_NOVELL                        0x40
60
#define PART_TYPE_NOVELL                        0x40
61
#define PART_TYPE_DYNAMIC                       0x42
61
#define PART_TYPE_DYNAMIC                       0x42
62
#define PART_TYPE_PCIX                          0x4B
62
#define PART_TYPE_PCIX                          0x4B
63
#define PART_TYPE_LINUX_SWAP            0x82
63
#define PART_TYPE_LINUX_SWAP            0x82
64
#define PART_TYPE_LINUX_NATIVE          0x83
64
#define PART_TYPE_LINUX_NATIVE          0x83
65
#define PART_TYPE_LINUX_LVM                     0x8E
65
#define PART_TYPE_LINUX_LVM                     0x8E
66
#define PART_TYPE_PHOENIXSAVE           0xA0
66
#define PART_TYPE_PHOENIXSAVE           0xA0
67
#define PART_TYPE_FREEBSD                       0xA5
67
#define PART_TYPE_FREEBSD                       0xA5
68
#define PART_TYPE_OPENBSD                       0xA6
68
#define PART_TYPE_OPENBSD                       0xA6
69
#define PART_TYPE_NETNBSD                       0xA9
69
#define PART_TYPE_NETNBSD                       0xA9
70
#define PART_TYPE_CPM                           0xDB
70
#define PART_TYPE_CPM                           0xDB
71
#define PART_TYPE_DBFS                          0xE0
71
#define PART_TYPE_DBFS                          0xE0
72
#define PART_TYPE_BBT                           0xFF
72
#define PART_TYPE_BBT                           0xFF
73
 
73
 
74
 
74
 
75
/*
75
/*
76
________________________________________________________________________________________________________________________________________
76
________________________________________________________________________________________________________________________________________
77
 
77
 
78
        Structure of the MasterBootRecord
78
        Structure of the MasterBootRecord
79
________________________________________________________________________________________________________________________________________
79
________________________________________________________________________________________________________________________________________
80
 
80
 
81
        Master Boot Record is 512 bytes long
81
        Master Boot Record is 512 bytes long
82
        The Master Boot Record is the same for pretty much all Operating Systems.
82
        The Master Boot Record is the same for pretty much all Operating Systems.
83
        It is located on the first Sector of the Hard Drive, at Cylinder 0, Head 0, Sector 1
83
        It is located on the first Sector of the Hard Drive, at Cylinder 0, Head 0, Sector 1
84
*/
84
*/
85
typedef struct
85
typedef struct
86
{
86
{
87
        uint8_t                         ExecutableCode[446];    // 446 bytes for machine start code
87
        uint8_t                         ExecutableCode[446];    // 446 bytes for machine start code
88
        PartitionEntry_t        PartitionEntry1;                // 16 bytes for partition entry 1
88
        PartitionEntry_t        PartitionEntry1;                // 16 bytes for partition entry 1
89
        PartitionEntry_t        PartitionEntry2;                // 16 bytes for partition entry 2
89
        PartitionEntry_t        PartitionEntry2;                // 16 bytes for partition entry 2
90
        PartitionEntry_t        PartitionEntry3;                // 16 bytes for partition entry 3
90
        PartitionEntry_t        PartitionEntry3;                // 16 bytes for partition entry 3
91
        PartitionEntry_t        PartitionEntry4;                // 16 bytes for partition entry 4
91
        PartitionEntry_t        PartitionEntry4;                // 16 bytes for partition entry 4
92
        uint16_t                        ExecutableMarker;               // BIOS-Signature (0x55 0xAA)
92
        uint16_t                        ExecutableMarker;               // BIOS-Signature (0x55 0xAA)
93
} __attribute__((packed)) MBR_Entry_t;
93
} __attribute__((packed)) MBR_Entry_t;
94
 
94
 
95
 
95
 
96
/*
96
/*
97
________________________________________________________________________________________________________________________________________
97
________________________________________________________________________________________________________________________________________
98
 
98
 
99
        Structure of the VolumeBootRecord
99
        Structure of the VolumeBootRecord
100
________________________________________________________________________________________________________________________________________
100
________________________________________________________________________________________________________________________________________
101
 
101
 
102
        The Volume Boot Record is 512 bytes long
102
        The Volume Boot Record is 512 bytes long
103
        This information is located in the first sector of every partition.
103
        This information is located in the first sector of every partition.
104
*/
104
*/
105
typedef struct
105
typedef struct
106
{
106
{
107
        uint8_t         JumpCode[3];                    // Jump Code + NOP
107
        uint8_t         JumpCode[3];                    // Jump Code + NOP
108
        int8_t          OEMName[8];                             // OEM Name
108
        int8_t          OEMName[8];                             // OEM Name
109
        uint16_t        BytesPerSector;                 // Bytes Per Sector
109
        uint16_t        BytesPerSector;                 // Bytes Per Sector
110
        uint8_t         SectorsPerCluster;              // Sectors Per Cluster
110
        uint8_t         SectorsPerCluster;              // Sectors Per Cluster
111
        uint16_t        ReservedSectors;                // Reserved Sectors
111
        uint16_t        ReservedSectors;                // Reserved Sectors
112
        uint8_t         NoFATCopies;                    // Number of Copies of FAT
112
        uint8_t         NoFATCopies;                    // Number of Copies of FAT
113
        uint16_t        MaxRootEntries;                 // Maximum Root Directory Entries
113
        uint16_t        MaxRootEntries;                 // Maximum Root Directory Entries
114
        uint16_t        NoSectorsInPartSml32MB; // Number of Sectors in Partition Smaller than 32 MB
114
        uint16_t        NoSectorsInPartSml32MB; // Number of Sectors in Partition Smaller than 32 MB
115
        uint8_t         MediaDescriptor;                // Media Descriptor (0xF8 for Hard Disks)
115
        uint8_t         MediaDescriptor;                // Media Descriptor (0xF8 for Hard Disks)
116
        uint16_t        SectorsPerFAT;                  // Sectors Per FAT
116
        uint16_t        SectorsPerFAT;                  // Sectors Per FAT
117
        uint16_t        SectorsPerTrack;                // Sectors Per Track
117
        uint16_t        SectorsPerTrack;                // Sectors Per Track
118
        uint16_t        NoHeads;                                // Number of Heads
118
        uint16_t        NoHeads;                                // Number of Heads
119
        uint32_t        NoHiddenSectors;                // Number of Hidden Sectors     in Partition
119
        uint32_t        NoHiddenSectors;                // Number of Hidden Sectors     in Partition
120
        uint32_t        NoSectors;                              // Number of Sectors in Partition
120
        uint32_t        NoSectors;                              // Number of Sectors in Partition
121
        uint16_t        DriveNo;                                // Logical Drive Number of Partition
121
        uint16_t        DriveNo;                                // Logical Drive Number of Partition
122
        uint8_t         ExtendedSig;                    // Extended Signature (0x29)
122
        uint8_t         ExtendedSig;                    // Extended Signature (0x29)
123
        uint32_t        SerialNo;                               // Serial Number of the Partition
123
        uint32_t        SerialNo;                               // Serial Number of the Partition
124
        int8_t          VolumeName[11];                 // Volume Name of the Partititon
124
        int8_t          VolumeName[11];                 // Volume Name of the Partititon
125
        int8_t          FATName[8];                             // FAT Name (FAT16)
125
        int8_t          FATName[8];                             // FAT Name (FAT16)
126
        uint8_t         ExecutableCode[446];    // 446 bytes for machine start code
126
        uint8_t         ExecutableCode[446];    // 446 bytes for machine start code
127
        uint16_t        ExecutableMarker;               // Executable Marker (0x55 0xAA)
127
        uint16_t        ExecutableMarker;               // Executable Marker (0x55 0xAA)
128
} __attribute__((packed)) VBR_Entry_t;
128
} __attribute__((packed)) VBR_Entry_t;
129
 
129
 
130
 
130
 
131
 
131
 
132
/*
132
/*
133
________________________________________________________________________________________________________________________________________
133
________________________________________________________________________________________________________________________________________
134
 
134
 
135
        Structure of an directory entry
135
        Structure of an directory entry
136
________________________________________________________________________________________________________________________________________
136
________________________________________________________________________________________________________________________________________
137
 
137
 
138
        Directory entry is 32 bytes.
138
        Directory entry is 32 bytes.
139
*/
139
*/
140
typedef struct
140
typedef struct
141
{
141
{
142
        int8_t          Name[8];                                        // 8 bytes name, padded with spaces.
142
        int8_t          Name[8];                                        // 8 bytes name, padded with spaces.
143
        uint8_t         Extension[3];                           // 3 bytes extension, padded with spaces.
143
        uint8_t         Extension[3];                           // 3 bytes extension, padded with spaces.
144
        uint8_t         Attribute;                                      // attribute of the directory entry (unused,archive,read-only,system,directory,volume)
144
        uint8_t         Attribute;                                      // attribute of the directory entry (unused,archive,read-only,system,directory,volume)
145
        uint8_t         Reserved[10];                           // reserved bytes within the directory entry.
145
        uint8_t         Reserved[10];                           // reserved bytes within the directory entry.
146
        uint32_t        DateTime;                                       // date and time of last write access to the file or directory.
146
        uint32_t        DateTime;                                       // date and time of last write access to the file or directory.
147
        uint16_t        StartCluster;                           // first cluster of the file or directory.
147
        uint16_t        StartCluster;                           // first cluster of the file or directory.
148
        uint32_t        Size;                                           // size of the file or directory in bytes.
148
        uint32_t        Size;                                           // size of the file or directory in bytes.
149
}  __attribute__((packed)) DirEntry_t;
149
}  __attribute__((packed)) DirEntry_t;
150
 
150
 
151
#define SLOT_EMPTY              0x00    // slot has never been used
151
#define SLOT_EMPTY              0x00    // slot has never been used
152
#define SLOT_E5                 0x05    // the real value is 0xe5
152
#define SLOT_E5                 0x05    // the real value is 0xe5
153
#define SLOT_DELETED            0xE5    // file in this slot deleted
153
#define SLOT_DELETED            0xE5    // file in this slot deleted
154
 
154
 
155
#define ATTR_NONE               0x00    // normal file
155
#define ATTR_NONE               0x00    // normal file
156
#define ATTR_READONLY           0x01    // file is readonly
156
#define ATTR_READONLY           0x01    // file is readonly
157
#define ATTR_HIDDEN                     0x02    // file is hidden
157
#define ATTR_HIDDEN                     0x02    // file is hidden
158
#define ATTR_SYSTEM                     0x04    // file is a system file
158
#define ATTR_SYSTEM                     0x04    // file is a system file
159
#define ATTR_VOLUMELABEL        0x08    // entry is a volume label
159
#define ATTR_VOLUMELABEL        0x08    // entry is a volume label
160
#define ATTR_LONG_FILENAME      0x0F    // this is a long filename entry
160
#define ATTR_LONG_FILENAME      0x0F    // this is a long filename entry
161
#define ATTR_SUBDIRECTORY       0x10    // entry is a directory name
161
#define ATTR_SUBDIRECTORY       0x10    // entry is a directory name
162
#define ATTR_ARCHIVE            0x20    // file is new or modified
162
#define ATTR_ARCHIVE            0x20    // file is new or modified
163
 
163
 
164
 
164
 
165
/*
165
/*
166
________________________________________________________________________________________________________________________________________
166
________________________________________________________________________________________________________________________________________
167
 
167
 
168
        Structure of an entry within the fileallocationtable.
168
        Structure of an entry within the fileallocationtable.
169
________________________________________________________________________________________________________________________________________
169
________________________________________________________________________________________________________________________________________
170
*/
170
*/
171
typedef struct
171
typedef struct
172
{
172
{
173
        uint16_t  NextCluster;                          // the next cluster of the file.
173
        uint16_t  NextCluster;                          // the next cluster of the file.
174
} __attribute__((packed)) Fat16Entry_t;
174
} __attribute__((packed)) Fat16Entry_t;
175
 
175
 
176
// secial fat entries
176
// secial fat entries
177
#define FAT16_CLUSTER_FREE                      0x0000
177
#define FAT16_CLUSTER_FREE                      0x0000
178
#define FAT16_CLUSTER_RESERVED          0x0001
178
#define FAT16_CLUSTER_RESERVED          0x0001
179
#define FAT16_CLUSTER_USED_MIN          0x0002
179
#define FAT16_CLUSTER_USED_MIN          0x0002
180
#define FAT16_CLUSTER_USED_MAX          0xFFEF
180
#define FAT16_CLUSTER_USED_MAX          0xFFEF
181
#define FAT16_CLUSTER_ROOTDIR_MIN       0xFFF0
181
#define FAT16_CLUSTER_ROOTDIR_MIN       0xFFF0
182
#define FAT16_CLUSTER_ROOTDIR_MAX       0xFFF6
182
#define FAT16_CLUSTER_ROOTDIR_MAX       0xFFF6
183
#define FAT16_CLUSTER_BAD                       0xFFF7
183
#define FAT16_CLUSTER_BAD                       0xFFF7
184
#define FAT16_CLUSTER_LAST_MIN          0xFFF8
184
#define FAT16_CLUSTER_LAST_MIN          0xFFF8
185
#define FAT16_CLUSTER_LAST_MAX          0xFFFF
185
#define FAT16_CLUSTER_LAST_MAX          0xFFFF
186
 
186
 
187
/*****************************************************************************************************************************************/
187
/*****************************************************************************************************************************************/
188
/*                                                                                                                                                                                                                                                                               */
188
/*                                                                                                                                                                                                                                                                               */
189
/*      Global variables needed for read- or write-acces to the FAT16- filesystem.                                                                                                                       */
189
/*      Global variables needed for read- or write-acces to the FAT16- filesystem.                                                                                                                       */
190
/*                                                                                                                                                                                                                                                                               */
190
/*                                                                                                                                                                                                                                                                               */
191
/*****************************************************************************************************************************************/
191
/*****************************************************************************************************************************************/
192
 
192
 
193
#define MBR_SECTOR                                      0x00    // the masterboot record is located in sector 0.
193
#define MBR_SECTOR                                      0x00    // the masterboot record is located in sector 0.
194
#define DIRENTRY_SIZE                           32              //bytes
194
#define DIRENTRY_SIZE                           32              //bytes
195
#define DIRENTRIES_PER_SECTOR           BYTES_PER_SECTOR/DIRENTRY_SIZE
195
#define DIRENTRIES_PER_SECTOR           BYTES_PER_SECTOR/DIRENTRY_SIZE
196
#define FAT16_BYTES                                     2
196
#define FAT16_BYTES                                     2
197
#define FAT16_ENTRIES_PER_SECTOR        BYTES_PER_SECTOR/FAT16_BYTES
197
#define FAT16_ENTRIES_PER_SECTOR        BYTES_PER_SECTOR/FAT16_BYTES
198
 
198
 
199
#define FSTATE_UNUSED   0
199
#define FSTATE_UNUSED   0
200
#define FSTATE_USED             1
200
#define FSTATE_USED             1
201
 
201
 
202
typedef struct
202
typedef struct
203
{
203
{
204
        uint8_t         IsValid;                                // 0 means invalid, else valid
204
        uint8_t         IsValid;                                // 0 means invalid, else valid
205
        uint8_t         SectorsPerCluster;              // how many sectors does a cluster contain?
205
        uint8_t         SectorsPerCluster;              // how many sectors does a cluster contain?
206
        uint8_t         FatCopies;                              // Numbers of copies of the FAT
206
        uint8_t         FatCopies;                              // Numbers of copies of the FAT
207
        uint16_t        MaxRootEntries;                 // Possible number of entries in the root directory.
207
        uint16_t        MaxRootEntries;                 // Possible number of entries in the root directory.
208
        uint16_t        SectorsPerFat;                  // how many sectors does a fat16 contain?
208
        uint16_t        SectorsPerFat;                  // how many sectors does a fat16 contain?
209
        uint32_t        FirstFatSector;                 // sector of the start of the fat
209
        uint32_t        FirstFatSector;                 // sector of the start of the fat
210
        uint32_t        FirstRootDirSector;             // sector of the rootdirectory
210
        uint32_t        FirstRootDirSector;             // sector of the rootdirectory
211
        uint32_t        FirstDataSector;                // sector of the first cluster containing data (cluster2).
211
        uint32_t        FirstDataSector;                // sector of the first cluster containing data (cluster2).
212
        uint32_t        LastDataSector;                 // the last data sector of the partition
212
        uint32_t        LastDataSector;                 // the last data sector of the partition
213
} Partition_t;
213
} Partition_t;
214
 
214
 
215
Partition_t     Partition;                                      // Structure holds partition information
215
Partition_t     Partition;                                      // Structure holds partition information
216
 
216
 
217
File_t FilePointer[FILE_MAX_OPEN];      // Allocate Memmoryspace for each filepointer used.
217
File_t FilePointer[FILE_MAX_OPEN];      // Allocate Memmoryspace for each filepointer used.
218
 
218
 
219
 
219
 
220
/****************************************************************************************************************************************/
220
/****************************************************************************************************************************************/
221
/*      Function:               FileDateTime(DateTime_t *);                                                                                                                                                                                     */
221
/*      Function:               FileDateTime(DateTime_t *);                                                                                                                                                                                     */
222
/*                                                                                                                                                                                                                                                                              */
222
/*                                                                                                                                                                                                                                                                              */
223
/*      Description:    This function calculates the DOS date time from a pointer to a time structure.                                                                          */
223
/*      Description:    This function calculates the DOS date time from a pointer to a time structure.                                                                          */
224
/*                                                                                                                                                                                                                                                                              */
224
/*                                                                                                                                                                                                                                                                              */
225
/*      Returnvalue:    Returns the DOS date time.                                                                                                                                                                                      */
225
/*      Returnvalue:    Returns the DOS date time.                                                                                                                                                                                      */
226
/****************************************************************************************************************************************/
226
/****************************************************************************************************************************************/
227
 
227
 
228
uint32_t FileDateTime(DateTime_t * pTimeStruct)
228
uint32_t FileDateTime(DateTime_t * pTimeStruct)
229
{
229
{
230
        uint32_t datetime = 0;
230
        uint32_t datetime = 0;
231
        if((pTimeStruct == 0) || !(pTimeStruct->Valid)) return datetime;
231
        if((pTimeStruct == 0) || !(pTimeStruct->Valid)) return datetime;
232
 
232
 
233
        datetime |= (0x0000007FL & (uint32_t)(pTimeStruct->Year - 1980))<<25; // set year
233
        datetime |= (0x0000007FL & (uint32_t)(pTimeStruct->Year - 1980))<<25; // set year
234
        datetime |= (0x0000000FL & (uint32_t)(pTimeStruct->Month))<<21; // set month
234
        datetime |= (0x0000000FL & (uint32_t)(pTimeStruct->Month))<<21; // set month
235
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Day))<<16;
235
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Day))<<16;
236
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Hour))<<11;
236
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Hour))<<11;
237
        datetime |= (0x0000003FL & (uint32_t)(pTimeStruct->Min))<<5;
237
        datetime |= (0x0000003FL & (uint32_t)(pTimeStruct->Min))<<5;
238
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Sec/2));
238
        datetime |= (0x0000001FL & (uint32_t)(pTimeStruct->Sec/2));
239
        return datetime;
239
        return datetime;
240
}
240
}
241
 
241
 
242
 
242
 
243
/****************************************************************************************************************************************/
243
/****************************************************************************************************************************************/
244
/*      Function:               LockFilePointer();                                                                                                                                                                                                      */
244
/*      Function:               LockFilePointer();                                                                                                                                                                                                      */
245
/*                                                                                                                                                                                                                                                                              */
245
/*                                                                                                                                                                                                                                                                              */
246
/*      Description:    This function trys to lock a free file pointer.                                                                                                                                         */
246
/*      Description:    This function trys to lock a free file pointer.                                                                                                                                         */
247
/*                                                                                                                                                                                                                                                                              */
247
/*                                                                                                                                                                                                                                                                              */
248
/*      Returnvalue:    Returns the Filepointer on success or 0.                                                                                                                                                        */
248
/*      Returnvalue:    Returns the Filepointer on success or 0.                                                                                                                                                        */
249
/****************************************************************************************************************************************/
249
/****************************************************************************************************************************************/
250
File_t * LockFilePointer(void)
250
File_t * LockFilePointer(void)
251
{
251
{
252
        uint8_t i;
252
        uint8_t i;
253
        File_t * File = 0;
253
        File_t * File = 0;
254
        for(i = 0; i < FILE_MAX_OPEN; i++)
254
        for(i = 0; i < FILE_MAX_OPEN; i++)
255
        {
255
        {
256
                if(FilePointer[i].State == FSTATE_UNUSED)               // found an unused one
256
                if(FilePointer[i].State == FSTATE_UNUSED)               // found an unused one
257
                {
257
                {
258
                        File = &FilePointer[i];                                         // set pointer to that entry
258
                        File = &FilePointer[i];                                         // set pointer to that entry
259
                        FilePointer[i].State = FSTATE_USED;                     // mark it as used
259
                        FilePointer[i].State = FSTATE_USED;                     // mark it as used
260
                        break;
260
                        break;
261
                }
261
                }
262
        }
262
        }
263
        return(File);
263
        return(File);
264
}
264
}
265
 
265
 
266
/****************************************************************************************************************************************/
266
/****************************************************************************************************************************************/
267
/*      Function:               UnlockFilePointer(file_t *);                                                                                                                                                                            */
267
/*      Function:               UnlockFilePointer(file_t *);                                                                                                                                                                            */
268
/*                                                                                                                                                                                                                                                                              */
268
/*                                                                                                                                                                                                                                                                              */
269
/*      Description:    This function trys to unlock a file pointer.                                                                                                                                            */
269
/*      Description:    This function trys to unlock a file pointer.                                                                                                                                            */
270
/*                                                                                                                                                                                                                                                                              */
270
/*                                                                                                                                                                                                                                                                              */
271
/*      Returnvalue:    Returns 1 if file pointer was freed else 0.                                                                                                                                                     */
271
/*      Returnvalue:    Returns 1 if file pointer was freed else 0.                                                                                                                                                     */
272
/****************************************************************************************************************************************/
272
/****************************************************************************************************************************************/
273
uint8_t UnlockFilePointer(File_t * file)
273
uint8_t UnlockFilePointer(File_t * file)
274
{
274
{
275
        uint8_t cnt;
275
        uint8_t cnt;
276
        if(file == NULL) return(0);
276
        if(file == NULL) return(0);
277
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
277
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
278
        {
278
        {
279
                if(&FilePointer[cnt] == file)                                           // filepointer to be freed found?
279
                if(&FilePointer[cnt] == file)                                           // filepointer to be freed found?
280
                {
280
                {
281
                        file->State = FSTATE_UNUSED;
281
                        file->State = FSTATE_UNUSED;
282
                        file->FirstSectorOfFirstCluster = 0;                    // Sectorpointer to the first sector of the first datacluster of the file.
282
                        file->FirstSectorOfFirstCluster = 0;                    // Sectorpointer to the first sector of the first datacluster of the file.
283
                        file->FirstSectorOfCurrCluster  = 0;
283
                        file->FirstSectorOfCurrCluster  = 0;
284
                        file->SectorOfCurrCluster               = 0;                    // Pointer to the cluster which is edited at the moment.
284
                        file->SectorOfCurrCluster               = 0;                    // Pointer to the cluster which is edited at the moment.
285
                        file->SectorOfCurrCluster               = 0;                    // The sector which is edited at the moment (cluster_pointer + sector_index).
285
                        file->SectorOfCurrCluster               = 0;                    // The sector which is edited at the moment (cluster_pointer + sector_index).
286
                        file->ByteOfCurrSector                  = 0;                    // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
286
                        file->ByteOfCurrSector                  = 0;                    // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
287
                        file->Mode                                              = 0;                    // mode of fileoperation (read,write)
287
                        file->Mode                                              = 0;                    // mode of fileoperation (read,write)
288
                        file->Size                                              = 0;                    // the size of the opend file in bytes.
288
                        file->Size                                              = 0;                    // the size of the opend file in bytes.
289
                        file->Position                                  = 0;                    // pointer to a character within the file 0 < fileposition < filesize
289
                        file->Position                                  = 0;                    // pointer to a character within the file 0 < fileposition < filesize
290
                        file->SectorInCache                     = 0;                    // the last sector read, wich is still in the sectorbuffer.
290
                        file->SectorInCache                     = 0;                    // the last sector read, wich is still in the sectorbuffer.
291
                        file->DirectorySector                   = 0;                    // the sectorposition where the directoryentry has been made.
291
                        file->DirectorySector                   = 0;                    // the sectorposition where the directoryentry has been made.
292
                        file->DirectoryIndex                    = 0;                    // the index to the directoryentry within the specified sector.
292
                        file->DirectoryIndex                    = 0;                    // the index to the directoryentry within the specified sector.
293
                        file->Attribute                                 = 0;                    // the attribute of the file opened.
293
                        file->Attribute                                 = 0;                    // the attribute of the file opened.
294
                        file = NULL;
294
                        file = NULL;
295
                        return(1);
295
                        return(1);
296
                }
296
                }
297
        }
297
        }
298
        return(0);
298
        return(0);
299
}
299
}
300
 
300
 
301
/****************************************************************************************************************************************/
301
/****************************************************************************************************************************************/
302
/*      Function:               SeperateDirName(int8_t*, int8_t*);                                                                                                                                                                              */
302
/*      Function:               SeperateDirName(int8_t*, int8_t*);                                                                                                                                                                              */
303
/*                                                                                                                                                                                                                                                                              */
303
/*                                                                                                                                                                                                                                                                              */
304
/*      Description:    This function seperates the first dirname from filepath and brings them                                                                                         */
304
/*      Description:    This function seperates the first dirname from filepath and brings them                                                                                         */
305
/*                                      into the needed format ('test.txt' -> 'TEST    TXT')                                                                                                                            */
305
/*                                      into the needed format ('test.txt' -> 'TEST    TXT')                                                                                                                            */
306
/*                                      The subpath is the pointer to the remaining substring if the filepath                                                                                           */
306
/*                                      The subpath is the pointer to the remaining substring if the filepath                                                                                           */
307
/*                                                                                                                                                                                                                                                                              */
307
/*                                                                                                                                                                                                                                                                              */
308
/*      Returnvalue:    Return NULL on error or pointer to subpath                                                                                                                                                                                                      */
308
/*      Returnvalue:    Return NULL on error or pointer to subpath                                                                                                                                                                                                      */
309
/****************************************************************************************************************************************/
309
/****************************************************************************************************************************************/
310
int8_t* SeperateDirName(const int8_t *filepath, int8_t *dirname)
310
int8_t* SeperateDirName(const int8_t *filepath, int8_t *dirname)
311
{
311
{
312
        int8_t* subpath = NULL;
312
        int8_t* subpath = NULL;
313
        uint8_t readpointer     = 0;
313
        uint8_t readpointer     = 0;
314
        uint8_t writepointer = 0;
314
        uint8_t writepointer = 0;
315
 
315
 
316
        // search subpath from beginning of filepath
316
        // search subpath from beginning of filepath
317
        subpath = NULL;
317
        subpath = NULL;
318
        readpointer     = 0;
318
        readpointer     = 0;
319
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
319
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
320
        while(subpath == NULL)  // search the filepath until a subpath was found.
320
        while(subpath == NULL)  // search the filepath until a subpath was found.
321
        {
321
        {
322
                if(((filepath[readpointer] == 0) || (filepath[readpointer] == '/')))    // if '/' found or end of filepath reached
322
                if(((filepath[readpointer] == 0) || (filepath[readpointer] == '/')))    // if '/' found or end of filepath reached
323
                {
323
                {
324
                        subpath = (int8_t*)&filepath[readpointer];                              // store the position of the first "/" found after the beginning of the filenpath
324
                        subpath = (int8_t*)&filepath[readpointer];                              // store the position of the first "/" found after the beginning of the filenpath
325
                }
325
                }
326
                readpointer++;
326
                readpointer++;
327
        }
327
        }
328
 
328
 
329
        // clear dirname with spaces
329
        // clear dirname with spaces
330
        dirname[11] = 0; // terminate dirname
330
        dirname[11] = 0; // terminate dirname
331
        for(writepointer = 0; writepointer < 11; writepointer++) dirname[writepointer] = ' ';
331
        for(writepointer = 0; writepointer < 11; writepointer++) dirname[writepointer] = ' ';
332
        writepointer = 0;
332
        writepointer = 0;
333
        // start seperating the dirname from the filepath.
333
        // start seperating the dirname from the filepath.
334
        readpointer = 0;
334
        readpointer = 0;
335
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
335
        if(filepath[0] == '/') readpointer = 1; // ignore first '/'
336
        while( &filepath[readpointer] < subpath)
336
        while( &filepath[readpointer] < subpath)
337
        {
337
        {
338
                if(writepointer >= 11) return(NULL);            // dirname to long
338
                if(writepointer >= 11) return(NULL);            // dirname to long
339
                if(filepath[readpointer] == '.')                        // seperating dirname and extension.
339
                if(filepath[readpointer] == '.')                        // seperating dirname and extension.
340
                {
340
                {
341
                        if(writepointer <= 8)
341
                        if(writepointer <= 8)
342
                        {
342
                        {
343
                                readpointer++;                                          // next character in filename
343
                                readpointer++;                                          // next character in filename
344
                                writepointer = 8;                                       // jump to start of extension
344
                                writepointer = 8;                                       // jump to start of extension
345
                        }
345
                        }
346
                        else return(NULL);                                              // dirbasename to long
346
                        else return(NULL);                                              // dirbasename to long
347
                }
347
                }
348
                else
348
                else
349
                {
349
                {
350
                        if((0x60 < filepath[readpointer]) && (filepath[readpointer] < 0x7B))
350
                        if((0x60 < filepath[readpointer]) && (filepath[readpointer] < 0x7B))
351
                        {
351
                        {
352
                                dirname[writepointer] = (filepath[readpointer] - 0x20);                                 // all characters must be upper case.
352
                                dirname[writepointer] = (filepath[readpointer] - 0x20);                                 // all characters must be upper case.
353
                        }
353
                        }
354
                        else
354
                        else
355
                        {
355
                        {
356
                                dirname[writepointer] = filepath[readpointer];
356
                                dirname[writepointer] = filepath[readpointer];
357
                        }
357
                        }
358
                        readpointer++;
358
                        readpointer++;
359
                        writepointer++;
359
                        writepointer++;
360
                }
360
                }
361
        }
361
        }
362
        return(subpath);
362
        return(subpath);
363
}
363
}
364
 
364
 
365
 
365
 
366
/**************************************************************************************************************************************+*/
366
/**************************************************************************************************************************************+*/
367
/*      Function:       Fat16ClusterToSector( uint16_t cluster);                                                                                                                                                                                */
367
/*      Function:       Fat16ClusterToSector( uint16_t cluster);                                                                                                                                                                                */
368
/*                                                                                                                                                                                                                                                                              */
368
/*                                                                                                                                                                                                                                                                              */
369
/*      Description:    This function converts a cluster number given by the fat to the corresponding                                                                           */
369
/*      Description:    This function converts a cluster number given by the fat to the corresponding                                                                           */
370
/*                                      sector that points to the start of the data area that is represented by the cluster number.                                                     */
370
/*                                      sector that points to the start of the data area that is represented by the cluster number.                                                     */
371
/*                                                                                                                                                                                                                                                                              */
371
/*                                                                                                                                                                                                                                                                              */
372
/*      Returnvalue: The sector number with the data area of the given cluster                                                                                                                          */
372
/*      Returnvalue: The sector number with the data area of the given cluster                                                                                                                          */
373
/****************************************************************************************************************************************/
373
/****************************************************************************************************************************************/
374
uint32_t        Fat16ClusterToSector(uint16_t cluster)
374
uint32_t        Fat16ClusterToSector(uint16_t cluster)
375
{
375
{
376
        if(!Partition.IsValid) return 0;
376
        if(!Partition.IsValid) return 0;
377
        if (cluster < 2) cluster = 2; // the 0. and 1. cluster in the fat are used for the media descriptor
377
        if (cluster < 2) cluster = 2; // the 0. and 1. cluster in the fat are used for the media descriptor
378
        return ( (cluster - 2) * Partition.SectorsPerCluster) + Partition.FirstDataSector; // the first data sector     is represented by the 2nd cluster
378
        return ( (cluster - 2) * Partition.SectorsPerCluster) + Partition.FirstDataSector; // the first data sector     is represented by the 2nd cluster
379
}
379
}
380
 
380
 
381
/****************************************************************************************************************************************/
381
/****************************************************************************************************************************************/
382
/*      Function:       SectorToFat16Cluster( uint32_t sector);                                                                                                                                                                         */
382
/*      Function:       SectorToFat16Cluster( uint32_t sector);                                                                                                                                                                         */
383
/*                                                                                                                                                                                                                                                                              */
383
/*                                                                                                                                                                                                                                                                              */
384
/*      Description:    This function converts a given sector number given to the corresponding                                                                                         */
384
/*      Description:    This function converts a given sector number given to the corresponding                                                                                         */
385
/*                                      cluster number in the fat that represents this data area.                                                                                                                       */
385
/*                                      cluster number in the fat that represents this data area.                                                                                                                       */
386
/*                                                                                                                                                                                                                                                                              */
386
/*                                                                                                                                                                                                                                                                              */
387
/*      Returnvalue: The cluster number representing the data area of the sector.                                                                                                                       */
387
/*      Returnvalue: The cluster number representing the data area of the sector.                                                                                                                       */
388
/****************************************************************************************************************************************/
388
/****************************************************************************************************************************************/
389
uint16_t        SectorToFat16Cluster(uint32_t sector)
389
uint16_t        SectorToFat16Cluster(uint32_t sector)
390
{
390
{
391
        if(!Partition.IsValid) return 0;
391
        if(!Partition.IsValid) return 0;
392
        return ((uint16_t)((sector - Partition.FirstDataSector) / Partition.SectorsPerCluster) + 2);
392
        return ((uint16_t)((sector - Partition.FirstDataSector) / Partition.SectorsPerCluster) + 2);
393
}
393
}
394
 
394
 
395
 
395
 
396
/****************************************************************************************************************************************/
396
/****************************************************************************************************************************************/
397
/*      Function:       Fat16_Deinit(void);                                                                                                                                                                                                             */
397
/*      Function:       Fat16_Deinit(void);                                                                                                                                                                                                             */
398
/*                                                                                                                                                                                                                                                                              */
398
/*                                                                                                                                                                                                                                                                              */
399
/*      Description:    This function uninitializes the fat 16 api                                                                                                                                                      */
399
/*      Description:    This function uninitializes the fat 16 api                                                                                                                                                      */
400
/*                                                                                                                                                                                                                                                                              */
400
/*                                                                                                                                                                                                                                                                              */
401
/*      Returnvalue: The function returns "0" on success                                                                                                                                                                        */
401
/*      Returnvalue: The function returns "0" on success                                                                                                                                                                        */
402
/****************************************************************************************************************************************/
402
/****************************************************************************************************************************************/
403
uint8_t Fat16_Deinit(void)
403
uint8_t Fat16_Deinit(void)
404
{
404
{
405
        int16_t returnvalue = 0;
405
        int16_t returnvalue = 0;
406
        uint8_t cnt;
406
        uint8_t cnt;
407
        // declare the filepointers as unused.
407
        // declare the filepointers as unused.
408
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
408
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
409
        {
409
        {
410
                if(FilePointer[cnt].State == FSTATE_USED)
410
                if(FilePointer[cnt].State == FSTATE_USED)
411
                {
411
                {
412
                        returnvalue += fclose_(&FilePointer[cnt]); // try to close open file pointers
412
                        returnvalue += fclose_(&FilePointer[cnt]); // try to close open file pointers
413
                }
413
                }
414
 
414
 
415
        }
415
        }
416
        SDC_Deinit();                   // uninitialize interface to sd-card
416
        SDC_Deinit();                   // uninitialize interface to sd-card
417
        Partition.IsValid = 0;  // mark data in partition structure as invalid
417
        Partition.IsValid = 0;  // mark data in partition structure as invalid
418
        return(returnvalue);
418
        return(returnvalue);
419
}
419
}
420
 
420
 
421
/****************************************************************************************************************************************/
421
/****************************************************************************************************************************************/
422
/*      Function:               Fat16_Init(void);                                                                                                                                                                                                       */
422
/*      Function:               Fat16_Init(void);                                                                                                                                                                                                       */
423
/*                                                                                                                                                                                                                                                                          */
423
/*                                                                                                                                                                                                                                                                          */
424
/*      Description:    This function reads the Masterbootrecord and finds the position of the Volumebootrecord, the FAT and the Rootdir    */
424
/*      Description:    This function reads the Masterbootrecord and finds the position of the Volumebootrecord, the FAT and the Rootdir    */
425
/*                                      and stores the information in global variables.                                                                                                                                     */
425
/*                                      and stores the information in global variables.                                                                                                                                     */
426
/*                                                                                                                                                                                                                                                                          */
426
/*                                                                                                                                                                                                                                                                          */
427
/*      Returnvalue:    The function returns "0" if the filesystem is initialized.                                                                                                                      */
427
/*      Returnvalue:    The function returns "0" if the filesystem is initialized.                                                                                                                      */
428
/****************************************************************************************************************************************/
428
/****************************************************************************************************************************************/
429
uint8_t Fat16_Init(void)
429
uint8_t Fat16_Init(void)
430
{
430
{
431
    uint8_t     cnt     = 0;
431
    uint8_t     cnt     = 0;
432
        uint32_t        partitionfirstsector;
432
        uint32_t        partitionfirstsector;
433
        VBR_Entry_t *VBR;
433
        VBR_Entry_t *VBR;
434
        MBR_Entry_t *MBR;
434
        MBR_Entry_t *MBR;
435
        File_t *file;
435
        File_t *file;
436
        uint8_t result = 0;
436
        uint8_t result = 0;
437
 
437
 
438
        printf("\r\n FAT16 init...");
438
        printf("\r\n FAT16 init...");
439
        Partition.IsValid = 0;
439
        Partition.IsValid = 0;
440
 
440
 
441
        // declare the filepointers as unused.
441
        // declare the filepointers as unused.
442
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
442
        for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++)
443
        {
443
        {
444
                FilePointer[cnt].State = FSTATE_UNUSED;
444
                FilePointer[cnt].State = FSTATE_UNUSED;
445
        }
445
        }
446
        // set current file pinter to first position in list
446
        // set current file pinter to first position in list
447
        file = &FilePointer[0];
447
        file = &FilePointer[0];
448
 
448
 
449
        // try to initialise the sd-card.
449
        // try to initialise the sd-card.
450
        if(SD_SUCCESS != SDC_Init())
450
        if(SD_SUCCESS != SDC_Init())
451
        {
451
        {
452
                printf("SD-Card could not be initialized.");
452
                printf("SD-Card could not be initialized.");
453
                result = 1;
453
                result = 1;
454
                goto end;
454
                goto end;
455
        }
455
        }
456
 
456
 
457
        // SD-Card is initialized successfully
457
        // SD-Card is initialized successfully
458
        if(SD_SUCCESS != SDC_GetSector((uint32_t)MBR_SECTOR,file->Cache))       // Read the MasterBootRecord
458
        if(SD_SUCCESS != SDC_GetSector((uint32_t)MBR_SECTOR,file->Cache))       // Read the MasterBootRecord
459
        {
459
        {
460
                printf("Error reading the MBR.");
460
                printf("Error reading the MBR.");
461
                result = 2;
461
                result = 2;
462
                goto end;
462
                goto end;
463
        }
463
        }
464
        MBR = (MBR_Entry_t *)file->Cache;                                               // Enter the MBR using the structure MBR_Entry_t.
464
        MBR = (MBR_Entry_t *)file->Cache;                                               // Enter the MBR using the structure MBR_Entry_t.
465
        if((MBR->PartitionEntry1.Type == PART_TYPE_FAT16_ST_32_MB) ||
465
        if((MBR->PartitionEntry1.Type == PART_TYPE_FAT16_ST_32_MB) ||
466
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16_LT_32_MB) ||
466
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16_LT_32_MB) ||
467
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16LBA))
467
           (MBR->PartitionEntry1.Type == PART_TYPE_FAT16LBA))
468
        {
468
        {
469
                // get sector offset 1st partition
469
                // get sector offset 1st partition
470
                partitionfirstsector = MBR->PartitionEntry1.NoSectorsBeforePartition;
470
                partitionfirstsector = MBR->PartitionEntry1.NoSectorsBeforePartition;
471
                // Start of Partition is the Volume Boot Sector
471
                // Start of Partition is the Volume Boot Sector
472
                if(SD_SUCCESS != SDC_GetSector(partitionfirstsector,file->Cache)) // Read the volume boot record
472
                if(SD_SUCCESS != SDC_GetSector(partitionfirstsector,file->Cache)) // Read the volume boot record
473
                {
473
                {
474
                        printf("Error reading the VBR.");
474
                        printf("Error reading the VBR.");
475
                        result = 3;
475
                        result = 3;
476
                        goto end;
476
                        goto end;
477
                }
477
                }
478
        }
478
        }
479
        else  // maybe the medium has no partition assuming sector 0 is the vbr
479
        else  // maybe the medium has no partition assuming sector 0 is the vbr
480
        {
480
        {
481
                partitionfirstsector = 0;
481
                partitionfirstsector = 0;
482
        }
482
        }
483
 
483
 
484
        VBR = (VBR_Entry_t *) file->Cache;                                              // Enter the VBR using the structure VBR_Entry_t.
484
        VBR = (VBR_Entry_t *) file->Cache;                                              // Enter the VBR using the structure VBR_Entry_t.
485
        if(VBR->BytesPerSector != BYTES_PER_SECTOR)
485
        if(VBR->BytesPerSector != BYTES_PER_SECTOR)
486
        {
486
        {
487
                printf("VBR: Sector size not supported.");
487
                printf("VBR: Sector size not supported.");
488
                result = 4;
488
                result = 4;
489
                goto end;
489
                goto end;
490
        }
490
        }
491
        Partition.SectorsPerCluster             = VBR->SectorsPerCluster;                       // Number of sectors per cluster. Depends on the memorysize of the sd-card.
491
        Partition.SectorsPerCluster             = VBR->SectorsPerCluster;                       // Number of sectors per cluster. Depends on the memorysize of the sd-card.
492
        Partition.FatCopies                     = VBR->NoFATCopies;                                     // Number of fatcopies.
492
        Partition.FatCopies                     = VBR->NoFATCopies;                                     // Number of fatcopies.
493
        Partition.MaxRootEntries                = VBR->MaxRootEntries;                          // How many Entries are possible in the rootdirectory (FAT16 allows max. 512 entries).
493
        Partition.MaxRootEntries                = VBR->MaxRootEntries;                          // How many Entries are possible in the rootdirectory (FAT16 allows max. 512 entries).
494
        Partition.SectorsPerFat                 = VBR->SectorsPerFAT;                           // The number of sectors per FAT.
494
        Partition.SectorsPerFat                 = VBR->SectorsPerFAT;                           // The number of sectors per FAT.
495
 
495
 
496
        /* Calculate the sectorpositon of the FAT, the Rootdirectory and the first Datacluster. */
496
        /* Calculate the sectorpositon of the FAT, the Rootdirectory and the first Datacluster. */
497
        // Calculate the position of the FileAllocationTable:
497
        // Calculate the position of the FileAllocationTable:
498
        // Start + # of Reserved Sectors
498
        // Start + # of Reserved Sectors
499
        Partition.FirstFatSector        =   (uint32_t)(partitionfirstsector + (uint32_t)(VBR->ReservedSectors));
499
        Partition.FirstFatSector        =   (uint32_t)(partitionfirstsector + (uint32_t)(VBR->ReservedSectors));
500
        // Calculate the position of the Rootdirectory:
500
        // Calculate the position of the Rootdirectory:
501
        // Start + # of Reserved Sectors + (# of Sectors Per FAT * # of FAT Copies)
501
        // Start + # of Reserved Sectors + (# of Sectors Per FAT * # of FAT Copies)
502
        Partition.FirstRootDirSector    =   Partition.FirstFatSector + (uint32_t)((uint32_t)Partition.SectorsPerFat*(uint32_t)Partition.FatCopies);
502
        Partition.FirstRootDirSector    =   Partition.FirstFatSector + (uint32_t)((uint32_t)Partition.SectorsPerFat*(uint32_t)Partition.FatCopies);
503
        // Calculate the position of the first datacluster:
503
        // Calculate the position of the first datacluster:
504
        // Start + # of Reserved + (# of Sectors Per FAT * # of FAT Copies) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
504
        // Start + # of Reserved + (# of Sectors Per FAT * # of FAT Copies) + ((Maximum Root Directory Entries * 32) / Bytes per Sector)
505
        Partition.FirstDataSector       =   Partition.FirstRootDirSector + (uint32_t)(Partition.MaxRootEntries>>4);  // assuming 512 Byte Per Sector
505
        Partition.FirstDataSector       =   Partition.FirstRootDirSector + (uint32_t)(Partition.MaxRootEntries>>4);  // assuming 512 Byte Per Sector
506
        // Calculate the last data sector
506
        // Calculate the last data sector
507
        if(VBR->NoSectors == 0)
507
        if(VBR->NoSectors == 0)
508
        {
508
        {
509
                printf("VBR: Bad number of sectors.");
509
                printf("VBR: Bad number of sectors.");
510
                result = 5;
510
                result = 5;
511
                goto end;
511
                goto end;
512
        }
512
        }
513
        Partition.LastDataSector = Partition.FirstDataSector + VBR->NoSectors - 1;
513
        Partition.LastDataSector = Partition.FirstDataSector + VBR->NoSectors - 1;
514
        // check for FAT16 in VBR of first partition
514
        // check for FAT16 in VBR of first partition
515
        if(!((VBR->FATName[0]=='F') && (VBR->FATName[1]=='A') && (VBR->FATName[2]=='T') && (VBR->FATName[3]=='1')&&(VBR->FATName[4]=='6')))
515
        if(!((VBR->FATName[0]=='F') && (VBR->FATName[1]=='A') && (VBR->FATName[2]=='T') && (VBR->FATName[3]=='1')&&(VBR->FATName[4]=='6')))
516
        {
516
        {
517
                printf("VBR: Partition ist not FAT16 type.");
517
                printf("VBR: Partition ist not FAT16 type.");
518
                result = 6;
518
                result = 6;
519
                goto end;
519
                goto end;
520
        }
520
        }
521
        Partition.IsValid = 1; // mark data in partition structure as valid
521
        Partition.IsValid = 1; // mark data in partition structure as valid
522
        result = 0;
522
        result = 0;
523
        end:
523
        end:
524
        if(result != 0) Fat16_Deinit();
524
        if(result != 0) Fat16_Deinit();
525
        else printf(" ...ok");
525
        else printf(" ...ok");
526
        return(result);
526
        return(result);
527
}
527
}
-
 
528
 
-
 
529
/****************************************************************************************************************************************/
-
 
530
/*      Function:       Fat16_IsValid(void);                                                                                                                                                                                                            */
-
 
531
/*                                                                                                                                                                                                                                                                              */
-
 
532
/*      Description:    This function return the Fat 15 filesystem state                                                                                                                                                        */
-
 
533
/*                                                                                                                                                                                                                                                                              */
-
 
534
/*      Returnvalue: The function returns "1" on success                                                                                                                                                                        */
-
 
535
/****************************************************************************************************************************************/
528
 
536
uint8_t Fat16_IsValid(void)
-
 
537
{
-
 
538
        return(Partition.IsValid);
529
 
539
}
530
 
540
 
531
/****************************************************************************************************************************************/
541
/****************************************************************************************************************************************/
532
/* Function:    ClearCurrCluster(File_t*);                                                                                                                                                                                      */
542
/* Function:    ClearCurrCluster(File_t*);                                                                                                                                                                                      */
533
/*                                                                                                                                                                                                                                                                              */
543
/*                                                                                                                                                                                                                                                                              */
534
/* Description: This function fills the current cluster with 0.                                                                                                                                                 */
544
/* Description: This function fills the current cluster with 0.                                                                                                                                                 */
535
/*                                                                                                                                                                                                                                                                              */
545
/*                                                                                                                                                                                                                                                                              */
536
/* Returnvalue: The function returns 1 on success else 0.                                                                                                                                                               */
546
/* Returnvalue: The function returns 1 on success else 0.                                                                                                                                                               */
537
/****************************************************************************************************************************************/
547
/****************************************************************************************************************************************/
538
uint8_t ClearCurrCluster(File_t * file)
548
uint8_t ClearCurrCluster(File_t * file)
539
{
549
{
540
        uint8_t retvalue = 1;
550
        uint8_t retvalue = 1;
541
        uint32_t i;
551
        uint32_t i;
542
 
552
 
543
        if((!Partition.IsValid) || (file == NULL)) return(0);
553
        if((!Partition.IsValid) || (file == NULL)) return(0);
544
 
554
 
545
        for(i = 0; i < BYTES_PER_SECTOR; i++) file->Cache[i] = 0; // clear file cache
555
        for(i = 0; i < BYTES_PER_SECTOR; i++) file->Cache[i] = 0; // clear file cache
546
        for(i = 0; i < Partition.SectorsPerCluster; i++)
556
        for(i = 0; i < Partition.SectorsPerCluster; i++)
547
        {
557
        {
548
                file->SectorInCache = file->FirstSectorOfCurrCluster + i;
558
                file->SectorInCache = file->FirstSectorOfCurrCluster + i;
549
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
559
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
550
                {
560
                {
551
                        Fat16_Deinit();
561
                        Fat16_Deinit();
552
                        retvalue = 0;
562
                        retvalue = 0;
553
                }
563
                }
554
        }
564
        }
555
        return(retvalue);
565
        return(retvalue);
556
}
566
}
557
 
567
 
558
/*****************************************************************************************************************************************/
568
/*****************************************************************************************************************************************/
559
/* Function:    GetNextCluster(File_t* );                                                                                                                                                                                        */
569
/* Function:    GetNextCluster(File_t* );                                                                                                                                                                                        */
560
/*                                                                                                                                                                                                                                                                               */
570
/*                                                                                                                                                                                                                                                                               */
561
/* Description: This function finds the next datacluster of the file specified with File *File.                                                                                  */
571
/* Description: This function finds the next datacluster of the file specified with File *File.                                                                                  */
562
/*                                                                                                                                                                                                                                                                               */
572
/*                                                                                                                                                                                                                                                                               */
563
/* Returnvalue: The function returns the next cluster or 0 if the last cluster has already reached.                                                                                                      */
573
/* Returnvalue: The function returns the next cluster or 0 if the last cluster has already reached.                                                                                                      */
564
/*****************************************************************************************************************************************/
574
/*****************************************************************************************************************************************/
565
uint16_t GetNextCluster(File_t * file)
575
uint16_t GetNextCluster(File_t * file)
566
{
576
{
567
        uint16_t cluster = 0;
577
        uint16_t cluster = 0;
568
        uint32_t fat_byte_offset, sector, byte;
578
        uint32_t fat_byte_offset, sector, byte;
569
        Fat16Entry_t * fat;
579
        Fat16Entry_t * fat;
570
 
580
 
571
        if((!Partition.IsValid) || (file == NULL)) return(cluster);
581
        if((!Partition.IsValid) || (file == NULL)) return(cluster);
572
        // if sector is within the data area
582
        // if sector is within the data area
573
        if((Partition.FirstDataSector <= file->FirstSectorOfCurrCluster)&& (file->FirstSectorOfCurrCluster <= Partition.LastDataSector))
583
        if((Partition.FirstDataSector <= file->FirstSectorOfCurrCluster)&& (file->FirstSectorOfCurrCluster <= Partition.LastDataSector))
574
        {
584
        {
575
                // determine current file cluster
585
                // determine current file cluster
576
                cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);
586
                cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);
577
                // calculate byte offset in the fat for corresponding entry
587
                // calculate byte offset in the fat for corresponding entry
578
                fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
588
                fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
579
                // calculate the sector that contains the current cluster within the fat
589
                // calculate the sector that contains the current cluster within the fat
580
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
590
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
581
                // calculate byte offset of the current cluster within that fat sector
591
                // calculate byte offset of the current cluster within that fat sector
582
                byte = fat_byte_offset % BYTES_PER_SECTOR;
592
                byte = fat_byte_offset % BYTES_PER_SECTOR;
583
                // read this sector to the file cache
593
                // read this sector to the file cache
584
                if(file->SectorInCache != sector)
594
                if(file->SectorInCache != sector)
585
                {
595
                {
586
                        file->SectorInCache = sector;                                           // update sector stored in buffer
596
                        file->SectorInCache = sector;                                           // update sector stored in buffer
587
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
597
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
588
                        {
598
                        {
589
                                Fat16_Deinit();
599
                                Fat16_Deinit();
590
                                return (cluster);
600
                                return (cluster);
591
                        }
601
                        }
592
                }
602
                }
593
                // read the next cluster from cache
603
                // read the next cluster from cache
594
                fat = (Fat16Entry_t *)(&(file->Cache[byte]));
604
                fat = (Fat16Entry_t *)(&(file->Cache[byte]));
595
                cluster = fat->NextCluster;
605
                cluster = fat->NextCluster;
596
                // if last cluster fat entry
606
                // if last cluster fat entry
597
                if(FAT16_CLUSTER_LAST_MIN <= cluster)
607
                if(FAT16_CLUSTER_LAST_MIN <= cluster)
598
                {
608
                {
599
                         cluster = 0;
609
                         cluster = 0;
600
                }
610
                }
601
                else
611
                else
602
                {
612
                {
603
                        file->FirstSectorOfCurrCluster = Fat16ClusterToSector(cluster);
613
                        file->FirstSectorOfCurrCluster = Fat16ClusterToSector(cluster);
604
                        file->SectorOfCurrCluster = 0;
614
                        file->SectorOfCurrCluster = 0;
605
                        file->ByteOfCurrSector = 0;
615
                        file->ByteOfCurrSector = 0;
606
                }
616
                }
607
        }
617
        }
608
        return(cluster);
618
        return(cluster);
609
}
619
}
610
 
620
 
611
 
621
 
612
/****************************************************************************************************************************************/
622
/****************************************************************************************************************************************/
613
/* Function:    FindNextFreeCluster(File_t *);                                                                                                                                                                          */
623
/* Function:    FindNextFreeCluster(File_t *);                                                                                                                                                                          */
614
/*                                                                                                                                                                                                                                                                              */
624
/*                                                                                                                                                                                                                                                                              */
615
/* Description: This function looks in the fat to find the next free cluster                                                                                                                    */
625
/* Description: This function looks in the fat to find the next free cluster                                                                                                                    */
616
/*                                                                                                                                                                                                                                                                              */
626
/*                                                                                                                                                                                                                                                                              */
617
/* Returnvalue: The function returns the cluster number of the next free cluster found within the fat.                                                                  */
627
/* Returnvalue: The function returns the cluster number of the next free cluster found within the fat.                                                                  */
618
/****************************************************************************************************************************************/
628
/****************************************************************************************************************************************/
619
uint16_t FindNextFreeCluster(File_t *file)
629
uint16_t FindNextFreeCluster(File_t *file)
620
{
630
{
621
        uint32_t fat_sector;                            // current sector within the fat relative to the first sector of the fat.
631
        uint32_t fat_sector;                            // current sector within the fat relative to the first sector of the fat.
622
        uint32_t curr_sector;                           // current sector
632
        uint32_t curr_sector;                           // current sector
623
        uint16_t fat_entry;                                     // index to an fatentry within the actual sector (256 fatentries are possible within one sector).
633
        uint16_t fat_entry;                                     // index to an fatentry within the actual sector (256 fatentries are possible within one sector).
624
        uint16_t free_cluster = 0;                      // next free cluster number.
634
        uint16_t free_cluster = 0;                      // next free cluster number.
625
        Fat16Entry_t * fat;
635
        Fat16Entry_t * fat;
626
 
636
 
627
        if((!Partition.IsValid) || (file == NULL)) return(0);
637
        if((!Partition.IsValid) || (file == NULL)) return(0);
628
 
638
 
629
        // start searching for an empty cluster at the beginning of the fat.
639
        // start searching for an empty cluster at the beginning of the fat.
630
        fat_sector = 0;
640
        fat_sector = 0;
631
        do
641
        do
632
        {
642
        {
633
                curr_sector = Partition.FirstFatSector + fat_sector;    // calculate sector to read
643
                curr_sector = Partition.FirstFatSector + fat_sector;    // calculate sector to read
634
                file->SectorInCache = curr_sector;                                              // upate the sector number of file cache.
644
                file->SectorInCache = curr_sector;                                              // upate the sector number of file cache.
635
                if( SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))              // read sector of fat from sd-card.
645
                if( SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))              // read sector of fat from sd-card.
636
                {
646
                {
637
                        Fat16_Deinit();
647
                        Fat16_Deinit();
638
                        return(free_cluster);
648
                        return(free_cluster);
639
                }
649
                }
640
 
650
 
641
                fat = (Fat16Entry_t *)file->Cache;                                              // set fat pointer to file cache
651
                fat = (Fat16Entry_t *)file->Cache;                                              // set fat pointer to file cache
642
 
652
 
643
                for(fat_entry = 0; fat_entry < FAT16_ENTRIES_PER_SECTOR; fat_entry++)                                           // look for an free cluster at all entries in this sector of the fat.
653
                for(fat_entry = 0; fat_entry < FAT16_ENTRIES_PER_SECTOR; fat_entry++)                                           // look for an free cluster at all entries in this sector of the fat.
644
                {
654
                {
645
                        if(fat[fat_entry].NextCluster == FAT16_CLUSTER_FREE)            // empty cluster found!!
655
                        if(fat[fat_entry].NextCluster == FAT16_CLUSTER_FREE)            // empty cluster found!!
646
                        {
656
                        {
647
                                fat[fat_entry].NextCluster = FAT16_CLUSTER_LAST_MAX;    // mark this fat-entry as used
657
                                fat[fat_entry].NextCluster = FAT16_CLUSTER_LAST_MAX;    // mark this fat-entry as used
648
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // and save the sector at the sd-card.
658
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // and save the sector at the sd-card.
649
                                {
659
                                {
650
                                        Fat16_Deinit();
660
                                        Fat16_Deinit();
651
                                        return(free_cluster);
661
                                        return(free_cluster);
652
                                }
662
                                }
653
                                free_cluster = (uint16_t)(fat_sector * FAT16_ENTRIES_PER_SECTOR + (uint32_t)fat_entry);
663
                                free_cluster = (uint16_t)(fat_sector * FAT16_ENTRIES_PER_SECTOR + (uint32_t)fat_entry);
654
                                fat_entry = FAT16_ENTRIES_PER_SECTOR;                                   // terminate the search for a free cluster in this sector.
664
                                fat_entry = FAT16_ENTRIES_PER_SECTOR;                                   // terminate the search for a free cluster in this sector.
655
                        }
665
                        }
656
                }
666
                }
657
                fat_sector++;                                                                                                   // continue the search in next fat sector
667
                fat_sector++;                                                                                                   // continue the search in next fat sector
658
        // repeat until the end of the fat is  reached and no free cluster has been found so far
668
        // repeat until the end of the fat is  reached and no free cluster has been found so far
659
        }while((fat_sector < Partition.SectorsPerFat) && (!free_cluster));
669
        }while((fat_sector < Partition.SectorsPerFat) && (!free_cluster));
660
        return(free_cluster);
670
        return(free_cluster);
661
}
671
}
662
 
672
 
663
 
673
 
664
/****************************************************************************************************************************************************/
674
/****************************************************************************************************************************************************/
665
/* Function:    int16_t fseek_(File_t *, int32_t *, uint8_t)                                                                                                                                                                                                            */
675
/* Function:    int16_t fseek_(File_t *, int32_t *, uint8_t)                                                                                                                                                                                                            */
666
/*                                                                                                                                                                                                                                                                                                      */
676
/*                                                                                                                                                                                                                                                                                                      */
667
/* Description: This function sets the pointer of the stream relative to the position                                                                                                                           */
677
/* Description: This function sets the pointer of the stream relative to the position                                                                                                                           */
668
/*                              specified by origin (SEEK_SET, SEEK_CUR, SEEK_END)                                                                                                                                                                      */
678
/*                              specified by origin (SEEK_SET, SEEK_CUR, SEEK_END)                                                                                                                                                                      */
669
/* Returnvalue: Is 1 if seek was successful                                                                                                                                                                                                                                                                     */
679
/* Returnvalue: Is 1 if seek was successful                                                                                                                                                                                                                                                                     */
670
/****************************************************************************************************************************************************/
680
/****************************************************************************************************************************************************/
671
int16_t fseek_(File_t * const file, int32_t offset, int16_t origin)
681
int16_t fseek_(File_t * const file, int32_t offset, int16_t origin)
672
{
682
{
673
        int32_t         fposition       = 0;
683
        int32_t         fposition       = 0;
674
        int16_t         retvalue        = 1;
684
        int16_t         retvalue        = 1;
675
 
685
 
676
        if((!Partition.IsValid) || (file == NULL)) return(0);
686
        if((!Partition.IsValid) || (file == NULL)) return(0);
677
        switch(origin)
687
        switch(origin)
678
        {
688
        {
679
                case SEEK_SET:                          // Fileposition relative to the beginning of the file.
689
                case SEEK_SET:                          // Fileposition relative to the beginning of the file.
680
                        fposition = 0;
690
                        fposition = 0;
681
                        break;
691
                        break;
682
                case SEEK_END:                          // Fileposition relative to the end of the file.
692
                case SEEK_END:                          // Fileposition relative to the end of the file.
683
                        fposition = (int32_t)file->Size;
693
                        fposition = (int32_t)file->Size;
684
                        break;
694
                        break;
685
                case SEEK_CUR:                          // Fileposition relative to the current position of the file.
695
                case SEEK_CUR:                          // Fileposition relative to the current position of the file.
686
                default:
696
                default:
687
                        fposition = file->Position;
697
                        fposition = file->Position;
688
                        break;
698
                        break;
689
        }
699
        }
690
 
700
 
691
        fposition += offset;
701
        fposition += offset;
692
 
702
 
693
        if((fposition >= 0) && (fposition <= (int32_t)file->Size))              // is the pointer still within the file?
703
        if((fposition >= 0) && (fposition <= (int32_t)file->Size))              // is the pointer still within the file?
694
        {
704
        {
695
                // reset file position to start of the file
705
                // reset file position to start of the file
696
                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
706
                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
697
                file->SectorOfCurrCluster       = 0;
707
                file->SectorOfCurrCluster       = 0;
698
                file->ByteOfCurrSector          = 0;
708
                file->ByteOfCurrSector          = 0;
699
                file->Position                          = 0;
709
                file->Position                          = 0;
700
 
710
 
701
                while(file->Position < fposition)       // repeat until the current position is less than target
711
                while(file->Position < fposition)       // repeat until the current position is less than target
702
                {
712
                {
703
                        file->Position++;                               // increment file position
713
                        file->Position++;                               // increment file position
704
                        file->ByteOfCurrSector++;               // next byte in current sector
714
                        file->ByteOfCurrSector++;               // next byte in current sector
705
                        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)
715
                        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)
706
                        {
716
                        {
707
                                file->ByteOfCurrSector = 0;                                                                             // reading at the beginning of new sector.
717
                                file->ByteOfCurrSector = 0;                                                                             // reading at the beginning of new sector.
708
                                file->SectorOfCurrCluster++;                                                                    // continue reading in next sector
718
                                file->SectorOfCurrCluster++;                                                                    // continue reading in next sector
709
                                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
719
                                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
710
                                {
720
                                {
711
                                        if(GetNextCluster(file))                                                                        // Sets the clusterpointer of the file to the next datacluster.
721
                                        if(GetNextCluster(file))                                                                        // Sets the clusterpointer of the file to the next datacluster.
712
                                        {
722
                                        {
713
                                                file->SectorOfCurrCluster = 0;
723
                                                file->SectorOfCurrCluster = 0;
714
                                        }
724
                                        }
715
                                        else // the last cluster was allready reached
725
                                        else // the last cluster was allready reached
716
                                        {
726
                                        {
717
                                                file->SectorOfCurrCluster--;                                                    // jump back to the ast sector in the last cluster
727
                                                file->SectorOfCurrCluster--;                                                    // jump back to the ast sector in the last cluster
718
                                                file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
728
                                                file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
719
                                        }
729
                                        }
720
                                }
730
                                }
721
                        }
731
                        }
722
                }
732
                }
723
        }
733
        }
724
        if(file->Position == fposition) retvalue = 0;
734
        if(file->Position == fposition) retvalue = 0;
725
        return(retvalue);
735
        return(retvalue);
726
}
736
}
727
 
737
 
728
 
738
 
729
/****************************************************************************************************************************************/
739
/****************************************************************************************************************************************/
730
/* Function:    uint16_t DeleteClusterChain(File *file);                                                                                                                                                                                */
740
/* Function:    uint16_t DeleteClusterChain(File *file);                                                                                                                                                                                */
731
/*                                                                                                                                                                                                                                                                              */
741
/*                                                                                                                                                                                                                                                                              */
732
/* Description: This function trances along a cluster chain in the fat and frees all clusters visited.                                                                  */
742
/* Description: This function trances along a cluster chain in the fat and frees all clusters visited.                                                                  */
733
/*                                                                                                                                                                                                                                                                              */
743
/*                                                                                                                                                                                                                                                                              */
734
/****************************************************************************************************************************************/
744
/****************************************************************************************************************************************/
735
uint8_t DeleteClusterChain(uint16_t StartCluster)
745
uint8_t DeleteClusterChain(uint16_t StartCluster)
736
{
746
{
737
        uint16_t cluster;
747
        uint16_t cluster;
738
        uint32_t fat_byte_offset, sector, byte;
748
        uint32_t fat_byte_offset, sector, byte;
739
        Fat16Entry_t * fat;
749
        Fat16Entry_t * fat;
740
        uint8_t buffer[BYTES_PER_SECTOR];
750
        uint8_t buffer[BYTES_PER_SECTOR];
741
        uint32_t sector_in_buffer = 0;
751
        uint32_t sector_in_buffer = 0;
742
        uint8_t repeat = 0;
752
        uint8_t repeat = 0;
743
 
753
 
744
        if(!Partition.IsValid) return 0;
754
        if(!Partition.IsValid) return 0;
745
 
755
 
746
        cluster = StartCluster; // init chain trace
756
        cluster = StartCluster; // init chain trace
747
        // calculate byte offset in the fat for corresponding entry
757
        // calculate byte offset in the fat for corresponding entry
748
        fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
758
        fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
749
        // calculate the sector that contains the current cluster within the fat
759
        // calculate the sector that contains the current cluster within the fat
750
        sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
760
        sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
751
        // calculate byte offset of the current cluster within that fat sector
761
        // calculate byte offset of the current cluster within that fat sector
752
        byte = fat_byte_offset % BYTES_PER_SECTOR;
762
        byte = fat_byte_offset % BYTES_PER_SECTOR;
753
        do
763
        do
754
        {
764
        {
755
                if(sector != sector_in_buffer)
765
                if(sector != sector_in_buffer)
756
                {
766
                {
757
                        // read this sector to buffer
767
                        // read this sector to buffer
758
                        sector_in_buffer = sector;
768
                        sector_in_buffer = sector;
759
                        if(SD_SUCCESS != SDC_GetSector(sector_in_buffer, buffer)) return 0;     // read sector from sd-card
769
                        if(SD_SUCCESS != SDC_GetSector(sector_in_buffer, buffer)) return 0;     // read sector from sd-card
760
                }
770
                }
761
                // read the next cluster from cache
771
                // read the next cluster from cache
762
                fat = (Fat16Entry_t *)(&(buffer[byte]));
772
                fat = (Fat16Entry_t *)(&(buffer[byte]));
763
                cluster = fat->NextCluster;
773
                cluster = fat->NextCluster;
764
                if((FAT16_CLUSTER_USED_MIN <= cluster) && (cluster <= FAT16_CLUSTER_USED_MAX) ) repeat = 1;
774
                if((FAT16_CLUSTER_USED_MIN <= cluster) && (cluster <= FAT16_CLUSTER_USED_MAX) ) repeat = 1;
765
                else repeat = 0;
775
                else repeat = 0;
766
 
776
 
767
                fat->NextCluster =      FAT16_CLUSTER_FREE; // mark current cluster as free
777
                fat->NextCluster =      FAT16_CLUSTER_FREE; // mark current cluster as free
768
                // calculate byte offset in the fat for corresponding entry
778
                // calculate byte offset in the fat for corresponding entry
769
                fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
779
                fat_byte_offset = ((uint32_t)cluster)<<1; // two FAT bytes (16 bits) for every cluster
770
                // calculate the sector that contains the current cluster within the fat
780
                // calculate the sector that contains the current cluster within the fat
771
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
781
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
772
                // calculate byte offset of the current cluster within that fat sector
782
                // calculate byte offset of the current cluster within that fat sector
773
                byte = fat_byte_offset % BYTES_PER_SECTOR;
783
                byte = fat_byte_offset % BYTES_PER_SECTOR;
774
                // if new sector is not the sector in buffer or the last cluster in the chain was traced
784
                // if new sector is not the sector in buffer or the last cluster in the chain was traced
775
                if((sector != sector_in_buffer) || !repeat)
785
                if((sector != sector_in_buffer) || !repeat)
776
                {       // write sector in buffer
786
                {       // write sector in buffer
777
                        if(SD_SUCCESS != SDC_PutSector(sector_in_buffer,buffer)) return 0;
787
                        if(SD_SUCCESS != SDC_PutSector(sector_in_buffer,buffer)) return 0;
778
                }
788
                }
779
        }
789
        }
780
        while(repeat);
790
        while(repeat);
781
 
791
 
782
        return 1;
792
        return 1;
783
}
793
}
784
 
794
 
785
 
795
 
786
/****************************************************************************************************************************************/
796
/****************************************************************************************************************************************/
787
/* Function:    uint16_t AppendCluster(File *file);                                                                                                                                                                                     */
797
/* Function:    uint16_t AppendCluster(File *file);                                                                                                                                                                                     */
788
/*                                                                                                                                                                                                                                                                              */
798
/*                                                                                                                                                                                                                                                                              */
789
/* Description: This function looks in the fat to find the next free cluster and appends it to the file.                                                                */
799
/* Description: This function looks in the fat to find the next free cluster and appends it to the file.                                                                */
790
/*                                                                                                                                                                                                                                                                              */
800
/*                                                                                                                                                                                                                                                                              */
791
/* Returnvalue: The function returns the appened cluster number or 0 of no cluster was appended.                                                                                                                                                */
801
/* Returnvalue: The function returns the appened cluster number or 0 of no cluster was appended.                                                                                                                                                */
792
/****************************************************************************************************************************************/
802
/****************************************************************************************************************************************/
793
uint16_t AppendCluster(File_t *file)
803
uint16_t AppendCluster(File_t *file)
794
{
804
{
795
        uint16_t last_cluster, new_cluster = 0;
805
        uint16_t last_cluster, new_cluster = 0;
796
        uint32_t fat_byte_offset, sector, byte;
806
        uint32_t fat_byte_offset, sector, byte;
797
        Fat16Entry_t * fat;
807
        Fat16Entry_t * fat;
798
 
808
 
799
        if((!Partition.IsValid) || (file == NULL)) return(new_cluster);
809
        if((!Partition.IsValid) || (file == NULL)) return(new_cluster);
800
 
810
 
801
        new_cluster = FindNextFreeCluster(file);        // the next free cluster found on the disk.
811
        new_cluster = FindNextFreeCluster(file);        // the next free cluster found on the disk.
802
        if(new_cluster)
812
        if(new_cluster)
803
        {       // A free cluster was found and can be added to the end of the file.
813
        {       // A free cluster was found and can be added to the end of the file.
804
                fseek_(file, 0, SEEK_END);                                                                                                      // jump to the end of the file
814
                fseek_(file, 0, SEEK_END);                                                                                                      // jump to the end of the file
805
                last_cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);            // determine current file cluster
815
                last_cluster = SectorToFat16Cluster(file->FirstSectorOfCurrCluster);            // determine current file cluster
806
                fat_byte_offset = ((uint32_t)last_cluster)<<1;
816
                fat_byte_offset = ((uint32_t)last_cluster)<<1;
807
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
817
                sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR);
808
                byte = fat_byte_offset % BYTES_PER_SECTOR;
818
                byte = fat_byte_offset % BYTES_PER_SECTOR;
809
 
819
 
810
                if(file->SectorInCache != sector)
820
                if(file->SectorInCache != sector)
811
                {
821
                {
812
                        file->SectorInCache = sector;                                           // update sector stored in buffer
822
                        file->SectorInCache = sector;                                           // update sector stored in buffer
813
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
823
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))       // read sector from sd-card
814
                        {
824
                        {
815
                                Fat16_Deinit();
825
                                Fat16_Deinit();
816
                                return(0);
826
                                return(0);
817
                        }
827
                        }
818
                }
828
                }
819
                fat = (Fat16Entry_t *)(&(file->Cache[byte]));
829
                fat = (Fat16Entry_t *)(&(file->Cache[byte]));
820
                fat->NextCluster = new_cluster;                                                 // append the free cluster to the end of the file in the FAT.
830
                fat->NextCluster = new_cluster;                                                 // append the free cluster to the end of the file in the FAT.
821
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // save the modified sector to the FAT.
831
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))               // save the modified sector to the FAT.
822
                {
832
                {
823
                        Fat16_Deinit();
833
                        Fat16_Deinit();
824
                        return(0);
834
                        return(0);
825
                }
835
                }
826
                file->FirstSectorOfCurrCluster = Fat16ClusterToSector(new_cluster);
836
                file->FirstSectorOfCurrCluster = Fat16ClusterToSector(new_cluster);
827
                file->SectorOfCurrCluster = 0;
837
                file->SectorOfCurrCluster = 0;
828
                file->ByteOfCurrSector = 0;
838
                file->ByteOfCurrSector = 0;
829
        }
839
        }
830
        return(new_cluster);
840
        return(new_cluster);
831
}
841
}
832
 
842
 
833
/****************************************************************************************************************************************************/
843
/****************************************************************************************************************************************************/
834
/* Function:    DirectoryEntryExist(int8_t *, uint8_t, uint8_t, File_t *)                                                                                                                                                                                       */
844
/* Function:    DirectoryEntryExist(int8_t *, uint8_t, uint8_t, File_t *)                                                                                                                                                                                       */
835
/*                                                                                                                                                                                                                                                                                                      */
845
/*                                                                                                                                                                                                                                                                                                      */
836
/* Description: This function searches all possible dir entries until the file or directory is found or the end of the directory is reached                     */
846
/* Description: This function searches all possible dir entries until the file or directory is found or the end of the directory is reached                     */
837
/*                                                                                                                                                                                                                                                                                                      */
847
/*                                                                                                                                                                                                                                                                                                      */
838
/* Returnvalue: This function returns 1 if the directory entry specified was found.                                                                                                                                     */
848
/* Returnvalue: This function returns 1 if the directory entry specified was found.                                                                                                                                     */
839
/****************************************************************************************************************************************************/
849
/****************************************************************************************************************************************************/
840
uint8_t DirectoryEntryExist(int8_t *dirname, uint8_t attribfilter, uint8_t attribmask, File_t *file)
850
uint8_t DirectoryEntryExist(int8_t *dirname, uint8_t attribfilter, uint8_t attribmask, File_t *file)
841
{
851
{
842
        uint32_t        dir_sector, max_dir_sector, curr_sector;
852
        uint32_t        dir_sector, max_dir_sector, curr_sector;
843
        uint16_t        dir_entry = 0;
853
        uint16_t        dir_entry = 0;
844
 
854
 
845
        uint16_t        end_of_directory_not_reached = 0;
855
        uint16_t        end_of_directory_not_reached = 0;
846
        uint8_t         i = 0;
856
        uint8_t         i = 0;
847
        uint8_t         direntry_exist = 0;
857
        uint8_t         direntry_exist = 0;
848
        DirEntry_t * dir;
858
        DirEntry_t * dir;
849
 
859
 
850
        // if incomming pointers are useless return immediatly
860
        // if incomming pointers are useless return immediatly
851
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return(direntry_exist);
861
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return(direntry_exist);
852
 
862
 
853
        // dir entries can be searched only in filesclusters that have
863
        // dir entries can be searched only in filesclusters that have
854
        // a corresponding dir entry with adir-flag set in its attribute
864
        // a corresponding dir entry with adir-flag set in its attribute
855
        // or direct within the root directory area
865
        // or direct within the root directory area
856
 
866
 
857
        file->FirstSectorOfFirstCluster = 0;
867
        file->FirstSectorOfFirstCluster = 0;
858
        // no current directory exist therefore assume searching in the root
868
        // no current directory exist therefore assume searching in the root
859
        if(file->DirectorySector == 0)
869
        if(file->DirectorySector == 0)
860
        {
870
        {
861
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
871
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
862
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
872
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
863
        }
873
        }
864
        // within the root directory area we can read sectors sequentially until the end of this area
874
        // within the root directory area we can read sectors sequentially until the end of this area
865
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
875
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
866
        {
876
        {
867
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
877
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
868
        }
878
        }
869
        // within the data clusters we can read sectors sequentially only within the cluster
879
        // within the data clusters we can read sectors sequentially only within the cluster
870
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
880
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
871
        {
881
        {
872
                max_dir_sector = Partition.SectorsPerCluster;                           // limit max secters before next cluster
882
                max_dir_sector = Partition.SectorsPerCluster;                           // limit max secters before next cluster
873
        }
883
        }
874
        else return (direntry_exist); // bad sector range for directory sector of the file
884
        else return (direntry_exist); // bad sector range for directory sector of the file
875
        // if search area is not defined yet
885
        // if search area is not defined yet
876
        if(file->FirstSectorOfFirstCluster == 0)
886
        if(file->FirstSectorOfFirstCluster == 0)
877
        {
887
        {
878
                // check if the directory entry of current file is existent and has the dir-flag set
888
                // check if the directory entry of current file is existent and has the dir-flag set
879
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
889
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
880
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
890
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
881
                {
891
                {
882
                        Fat16_Deinit();
892
                        Fat16_Deinit();
883
                        return(direntry_exist);
893
                        return(direntry_exist);
884
                }
894
                }
885
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
895
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
886
                switch((uint8_t)dir[file->DirectoryIndex].Name[0])                                      // check if current directory exist
896
                switch((uint8_t)dir[file->DirectoryIndex].Name[0])                                      // check if current directory exist
887
                {
897
                {
888
                        case SLOT_EMPTY:
898
                        case SLOT_EMPTY:
889
                        case SLOT_DELETED:
899
                        case SLOT_DELETED:
890
                                // the directrory pointer of this file points to a deleted or not existen directory
900
                                // the directrory pointer of this file points to a deleted or not existen directory
891
                                // therefore no file or subdirectory can be created
901
                                // therefore no file or subdirectory can be created
892
                                return (direntry_exist);
902
                                return (direntry_exist);
893
                                break;
903
                                break;
894
                        default:        // and is a real directory
904
                        default:        // and is a real directory
895
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
905
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
896
                                {       // current file is not a directory therefore no file or subdirectory can be created here
906
                                {       // current file is not a directory therefore no file or subdirectory can be created here
897
                                        return (direntry_exist);
907
                                        return (direntry_exist);
898
                                }
908
                                }
899
                                break;
909
                                break;
900
                }
910
                }
901
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[file->DirectoryIndex].StartCluster);
911
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[file->DirectoryIndex].StartCluster);
902
        }
912
        }
903
 
913
 
904
        // update current file data area position to start of first cluster
914
        // update current file data area position to start of first cluster
905
        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
915
        file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
906
        file->SectorOfCurrCluster               = 0;
916
        file->SectorOfCurrCluster               = 0;
907
        file->ByteOfCurrSector                  = 0;
917
        file->ByteOfCurrSector                  = 0;
908
 
918
 
909
        do // loop over all data clusters of the current directory entry
919
        do // loop over all data clusters of the current directory entry
910
        {
920
        {
911
                dir_sector = 0; // reset sector counter within a new cluster
921
                dir_sector = 0; // reset sector counter within a new cluster
912
                do // loop over all sectors of a cluster or all sectors of the root directory
922
                do // loop over all sectors of a cluster or all sectors of the root directory
913
                {
923
                {
914
                        curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
924
                        curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
915
                        file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
925
                        file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
916
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read the sector
926
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read the sector
917
                        {
927
                        {
918
                                Fat16_Deinit();
928
                                Fat16_Deinit();
919
                                return(direntry_exist);
929
                                return(direntry_exist);
920
                        }
930
                        }
921
                        dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
931
                        dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
922
                        // search all directory entries within that sector
932
                        // search all directory entries within that sector
923
                        for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
933
                        for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
924
                        {   // check for existing dir entry
934
                        {   // check for existing dir entry
925
                                switch((uint8_t)dir[dir_entry].Name[0])
935
                                switch((uint8_t)dir[dir_entry].Name[0])
926
                                {
936
                                {
927
                                        case SLOT_EMPTY:
937
                                        case SLOT_EMPTY:
928
                                        case SLOT_DELETED:
938
                                        case SLOT_DELETED:
929
                                                // ignore empty or deleted dir entries
939
                                                // ignore empty or deleted dir entries
930
                                                break;
940
                                                break;
931
                                        default:
941
                                        default:
932
                                                // if existing check attributes before names are compared will safe performance
942
                                                // if existing check attributes before names are compared will safe performance
933
                                                if ((dir[dir_entry].Attribute & attribmask) != attribfilter) break; // attribute must match
943
                                                if ((dir[dir_entry].Attribute & attribmask) != attribfilter) break; // attribute must match
934
                                                // then compare the name to the giveb dirname (first 11 characters include 8 chars of basename and 3 chars extension.)
944
                                                // then compare the name to the giveb dirname (first 11 characters include 8 chars of basename and 3 chars extension.)
935
                                                i = 0;
945
                                                i = 0;
936
                                                while((i < 11) && (dir[dir_entry].Name[i] == dirname[i])) i++;
946
                                                while((i < 11) && (dir[dir_entry].Name[i] == dirname[i])) i++;
937
                                                if (i < 10) break; // names does not match
947
                                                if (i < 10) break; // names does not match
938
                                                // if dirname and attribute have matched
948
                                                // if dirname and attribute have matched
939
                                                file->Attribute = dir[dir_entry].Attribute; // store attribute of found dir entry
949
                                                file->Attribute = dir[dir_entry].Attribute; // store attribute of found dir entry
940
                                                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[dir_entry].StartCluster); // set sector of first data cluster
950
                                                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dir[dir_entry].StartCluster); // set sector of first data cluster
941
                                                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
951
                                                file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
942
                                                file->SectorOfCurrCluster = 0;
952
                                                file->SectorOfCurrCluster = 0;
943
                                                file->ByteOfCurrSector = 0;
953
                                                file->ByteOfCurrSector = 0;
944
                                                file->DirectorySector = curr_sector; // current sector
954
                                                file->DirectorySector = curr_sector; // current sector
945
                                                file->DirectoryIndex  = dir_entry; // current direntry in current sector
955
                                                file->DirectoryIndex  = dir_entry; // current direntry in current sector
946
                                                file->Size = dir[dir_entry].Size;
956
                                                file->Size = dir[dir_entry].Size;
947
                                                direntry_exist = 1; // mark as found
957
                                                direntry_exist = 1; // mark as found
948
                                                dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
958
                                                dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
949
                                } // end of first byte of name check
959
                                } // end of first byte of name check
950
                        }
960
                        }
951
                        dir_sector++; // search next sector
961
                        dir_sector++; // search next sector
952
                // stop if we reached the end of the cluster or the end of the root dir
962
                // stop if we reached the end of the cluster or the end of the root dir
953
                }while((dir_sector < max_dir_sector) && (!direntry_exist));
963
                }while((dir_sector < max_dir_sector) && (!direntry_exist));
954
 
964
 
955
                // if we are seaching in the data area and the file not found in this cluster so take next cluster.
965
                // if we are seaching in the data area and the file not found in this cluster so take next cluster.
956
                if(!direntry_exist && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
966
                if(!direntry_exist && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
957
                {
967
                {
958
                        end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
968
                        end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
959
                }
969
                }
960
        }while((end_of_directory_not_reached) && (!direntry_exist)); // repeat until a next cluster exist an no
970
        }while((end_of_directory_not_reached) && (!direntry_exist)); // repeat until a next cluster exist an no
961
        return(direntry_exist);
971
        return(direntry_exist);
962
}
972
}
963
 
973
 
964
 
974
 
965
/****************************************************************************************************************************************/
975
/****************************************************************************************************************************************/
966
/*      Function:               CreateDirectoryEntry(int8_t *, uint16_t, File_t *)                                                                                                                                                      */
976
/*      Function:               CreateDirectoryEntry(int8_t *, uint16_t, File_t *)                                                                                                                                                      */
967
/*                                                                                                                                                                                                                                                                              */
977
/*                                                                                                                                                                                                                                                                              */
968
/*      Description:    This function looks for the next free position in the directory and creates an entry.                                                           */
978
/*      Description:    This function looks for the next free position in the directory and creates an entry.                                                           */
969
/*                                      The type of an directory entry is specified by the file attribute.                                                                                                      */
979
/*                                      The type of an directory entry is specified by the file attribute.                                                                                                      */
970
/*                                                                                                                                                                                                                                                                              */
980
/*                                                                                                                                                                                                                                                                              */
971
/*      Returnvalue:    Return 0 on error                                                                                                                                                                                                       */
981
/*      Returnvalue:    Return 0 on error                                                                                                                                                                                                       */
972
/****************************************************************************************************************************************/
982
/****************************************************************************************************************************************/
973
uint8_t CreateDirectoryEntry(int8_t *dirname, uint8_t attrib, File_t *file)
983
uint8_t CreateDirectoryEntry(int8_t *dirname, uint8_t attrib, File_t *file)
974
{
984
{
975
        uint32_t        dir_sector, max_dir_sector, curr_sector;
985
        uint32_t        dir_sector, max_dir_sector, curr_sector;
976
        uint16_t        dir_entry       = 0;
986
        uint16_t        dir_entry       = 0;
977
        uint16_t        subdircluster, dircluster = 0;
987
        uint16_t        subdircluster, dircluster = 0;
978
        uint16_t        end_of_directory_not_reached = 0;
988
        uint16_t        end_of_directory_not_reached = 0;
979
        uint8_t         i                       = 0;
989
        uint8_t         i                       = 0;
980
        uint8_t         retvalue        = 0;
990
        uint8_t         retvalue        = 0;
981
        DirEntry_t*     dir;
991
        DirEntry_t*     dir;
982
 
992
 
983
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return (retvalue);
993
        if((!Partition.IsValid) || (file == NULL) || (dirname == NULL)) return (retvalue);
984
        // It is not checked here that the dir entry that should be created is already existent!
994
        // It is not checked here that the dir entry that should be created is already existent!
985
 
995
 
986
        // Dir entries can be created only in file-clusters that have
996
        // Dir entries can be created only in file-clusters that have
987
        // the dir-flag set in its attribute or within the root directory
997
        // the dir-flag set in its attribute or within the root directory
988
 
998
 
989
        file->FirstSectorOfFirstCluster = 0;
999
        file->FirstSectorOfFirstCluster = 0;
990
        // no current directory exist therefore assume creating in the root
1000
        // no current directory exist therefore assume creating in the root
991
        if(file->DirectorySector == 0)
1001
        if(file->DirectorySector == 0)
992
        {
1002
        {
993
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1003
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
994
                dircluster = 0;
1004
                dircluster = 0;
995
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
1005
                file->FirstSectorOfFirstCluster = Partition.FirstRootDirSector;
996
        }
1006
        }
997
        // within the root directory area we can read sectors sequentially until the end of this area
1007
        // within the root directory area we can read sectors sequentially until the end of this area
998
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
1008
        else if((Partition.FirstRootDirSector <= file->DirectorySector) && (file->DirectorySector < Partition.FirstDataSector))
999
        {
1009
        {
1000
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1010
                max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR;
1001
        }
1011
        }
1002
        // within the data clusters we can read sectors sequentially only within the cluster
1012
        // within the data clusters we can read sectors sequentially only within the cluster
1003
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
1013
        else if((Partition.FirstDataSector <= file->DirectorySector) && (file->DirectorySector <= Partition.LastDataSector))
1004
        {
1014
        {
1005
                max_dir_sector = Partition.SectorsPerCluster;
1015
                max_dir_sector = Partition.SectorsPerCluster;
1006
        }
1016
        }
1007
        else return (retvalue); // bad sector range for directory sector of the file
1017
        else return (retvalue); // bad sector range for directory sector of the file
1008
        // if search area is not defined yet
1018
        // if search area is not defined yet
1009
        if(file->FirstSectorOfFirstCluster == 0)
1019
        if(file->FirstSectorOfFirstCluster == 0)
1010
        {
1020
        {
1011
            // check if the directory entry of current file is existent and has the dir-flag set
1021
            // check if the directory entry of current file is existent and has the dir-flag set
1012
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
1022
                file->SectorInCache = file->DirectorySector;                            // update the sector number of file cache.
1013
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1023
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1014
                {
1024
                {
1015
                        Fat16_Deinit();
1025
                        Fat16_Deinit();
1016
                        return(retvalue);
1026
                        return(retvalue);
1017
                }
1027
                }
1018
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1028
                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1019
                switch((uint8_t)dir[file->DirectoryIndex].Name[0])                                      // check if current directory exist
1029
                switch((uint8_t)dir[file->DirectoryIndex].Name[0])                                      // check if current directory exist
1020
                {
1030
                {
1021
                        case SLOT_EMPTY:
1031
                        case SLOT_EMPTY:
1022
                        case SLOT_DELETED:
1032
                        case SLOT_DELETED:
1023
                                return (retvalue);
1033
                                return (retvalue);
1024
                                break;
1034
                                break;
1025
                        default:        // and is a real directory
1035
                        default:        // and is a real directory
1026
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
1036
                                if((dir[file->DirectoryIndex].Attribute & ATTR_SUBDIRECTORY) != ATTR_SUBDIRECTORY)
1027
                                {       // current file is not a directory therefore no file or subdirectory can be created here
1037
                                {       // current file is not a directory therefore no file or subdirectory can be created here
1028
                                        return (retvalue);
1038
                                        return (retvalue);
1029
                                }
1039
                                }
1030
                                break;
1040
                                break;
1031
                }
1041
                }
1032
                dircluster = dir[file->DirectoryIndex].StartCluster;
1042
                dircluster = dir[file->DirectoryIndex].StartCluster;
1033
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dircluster);
1043
                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(dircluster);
1034
        }
1044
        }
1035
 
1045
 
1036
        subdircluster = FindNextFreeCluster(file);      // get the next free cluster on the disk and mark it as used.
1046
        subdircluster = FindNextFreeCluster(file);      // get the next free cluster on the disk and mark it as used.
1037
        if(subdircluster)
1047
        if(subdircluster)
1038
        {
1048
        {
1039
                file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
1049
                file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;
1040
                file->SectorOfCurrCluster               = 0;
1050
                file->SectorOfCurrCluster               = 0;
1041
                do // loop over all clusters of current directory
1051
                do // loop over all clusters of current directory
1042
                {
1052
                {
1043
                        dir_sector = 0; // reset sector counter within a new cluster
1053
                        dir_sector = 0; // reset sector counter within a new cluster
1044
                        do // loop over all sectors of a cluster or all sectors of the root directory
1054
                        do // loop over all sectors of a cluster or all sectors of the root directory
1045
                        {
1055
                        {
1046
                                curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
1056
                                curr_sector = file->FirstSectorOfCurrCluster + dir_sector;      // calculate sector number
1047
                                file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
1057
                                file->SectorInCache = curr_sector;                                                      // upate the sector number of file cache.
1048
                                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1058
                                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1049
                                {
1059
                                {
1050
                                        Fat16_Deinit();
1060
                                        Fat16_Deinit();
1051
                                        return(retvalue);
1061
                                        return(retvalue);
1052
                                }
1062
                                }
1053
                                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1063
                                dir = (DirEntry_t *)file->Cache;                                                        // set pointer to directory
1054
                                // search all directory entries of a sector
1064
                                // search all directory entries of a sector
1055
                                for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
1065
                                for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++)
1056
                                {       // check if current direntry is available
1066
                                {       // check if current direntry is available
1057
                                        if(((uint8_t)dir[dir_entry].Name[0] == SLOT_EMPTY) || ((uint8_t)dir[dir_entry].Name[0] == SLOT_DELETED))
1067
                                        if(((uint8_t)dir[dir_entry].Name[0] == SLOT_EMPTY) || ((uint8_t)dir[dir_entry].Name[0] == SLOT_DELETED))
1058
                                        {       // a free direntry was found
1068
                                        {       // a free direntry was found
1059
                                                for(i = 0; i < 11; i++) dir[dir_entry].Name[i] = dirname[i];            // Set dir name
1069
                                                for(i = 0; i < 11; i++) dir[dir_entry].Name[i] = dirname[i];            // Set dir name
1060
                                                dir[dir_entry].Attribute    = attrib;                                                           // Set the attribute of the new directoryentry.
1070
                                                dir[dir_entry].Attribute    = attrib;                                                           // Set the attribute of the new directoryentry.
1061
                                                dir[dir_entry].StartCluster = subdircluster;                                            // copy the location of the first datacluster to the directoryentry.
1071
                                                dir[dir_entry].StartCluster = subdircluster;                                            // copy the location of the first datacluster to the directoryentry.
1062
                                                dir[dir_entry].DateTime         = FileDateTime(&SystemTime);                    // set date/time
1072
                                                dir[dir_entry].DateTime         = FileDateTime(&SystemTime);                    // set date/time
1063
                                                dir[dir_entry].Size             = 0;                                                                    // the new createted file has no content yet.
1073
                                                dir[dir_entry].Size             = 0;                                                                    // the new createted file has no content yet.
1064
                                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to card
1074
                                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to card
1065
                                                {
1075
                                                {
1066
                                                        Fat16_Deinit();
1076
                                                        Fat16_Deinit();
1067
                                                        return(retvalue);
1077
                                                        return(retvalue);
1068
                                                }
1078
                                                }
1069
                                                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(subdircluster);  // Calculate absolute sectorposition of first datacluster.
1079
                                                file->FirstSectorOfFirstCluster = Fat16ClusterToSector(subdircluster);  // Calculate absolute sectorposition of first datacluster.
1070
                                                file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;      // Start reading the file with the first sector of the first datacluster.
1080
                                                file->FirstSectorOfCurrCluster  = file->FirstSectorOfFirstCluster;      // Start reading the file with the first sector of the first datacluster.
1071
                                                file->SectorOfCurrCluster               = 0;                                                            // reset sector of cureen cluster
1081
                                                file->SectorOfCurrCluster               = 0;                                                            // reset sector of cureen cluster
1072
                                                file->ByteOfCurrSector                  = 0;                                                            // reset the byte location within the current sector
1082
                                                file->ByteOfCurrSector                  = 0;                                                            // reset the byte location within the current sector
1073
                                                file->Attribute                                 = attrib;                                               // set file attribute to dir attribute
1083
                                                file->Attribute                                 = attrib;                                               // set file attribute to dir attribute
1074
                                                file->Size                                              = 0;                                                        // new file has no size
1084
                                                file->Size                                              = 0;                                                        // new file has no size
1075
                                                file->DirectorySector                   = curr_sector;
1085
                                                file->DirectorySector                   = curr_sector;
1076
                                                file->DirectoryIndex                    = dir_entry;
1086
                                                file->DirectoryIndex                    = dir_entry;
1077
                                                if((attrib & ATTR_SUBDIRECTORY) == ATTR_SUBDIRECTORY)                           // if a new directory was created then initilize the data area
1087
                                                if((attrib & ATTR_SUBDIRECTORY) == ATTR_SUBDIRECTORY)                           // if a new directory was created then initilize the data area
1078
                                                {
1088
                                                {
1079
                                                        ClearCurrCluster(file); // fill cluster with zeros
1089
                                                        ClearCurrCluster(file); // fill cluster with zeros
1080
                                                        file->SectorInCache = file->FirstSectorOfFirstCluster;
1090
                                                        file->SectorInCache = file->FirstSectorOfFirstCluster;
1081
                                                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1091
                                                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))// read in the sector.
1082
                                                        {
1092
                                                        {
1083
                                                                Fat16_Deinit();
1093
                                                                Fat16_Deinit();
1084
                                                                return(retvalue);
1094
                                                                return(retvalue);
1085
                                                        }
1095
                                                        }
1086
                                                        dir = (DirEntry_t *)file->Cache;
1096
                                                        dir = (DirEntry_t *)file->Cache;
1087
                                                        // create direntry "." to current dir
1097
                                                        // create direntry "." to current dir
1088
                                                        dir[0].Name[0] = 0x2E;
1098
                                                        dir[0].Name[0] = 0x2E;
1089
                                                        for(i = 1; i < 11; i++) dir[0].Name[i] = ' ';
1099
                                                        for(i = 1; i < 11; i++) dir[0].Name[i] = ' ';
1090
                                                        dir[0].Attribute = ATTR_SUBDIRECTORY;
1100
                                                        dir[0].Attribute = ATTR_SUBDIRECTORY;
1091
                                                        dir[0].StartCluster = subdircluster;
1101
                                                        dir[0].StartCluster = subdircluster;
1092
                                                        dir[0].DateTime = 0;
1102
                                                        dir[0].DateTime = 0;
1093
                                                        dir[0].Size = 0;
1103
                                                        dir[0].Size = 0;
1094
                                                        // create direntry ".." to the upper dir
1104
                                                        // create direntry ".." to the upper dir
1095
                                                        dir[1].Name[0] = 0x2E;
1105
                                                        dir[1].Name[0] = 0x2E;
1096
                                                        dir[1].Name[1] = 0x2E;
1106
                                                        dir[1].Name[1] = 0x2E;
1097
                                                        for(i = 2; i < 11; i++) dir[1].Name[i] = ' ';
1107
                                                        for(i = 2; i < 11; i++) dir[1].Name[i] = ' ';
1098
                                                        dir[1].Attribute = ATTR_SUBDIRECTORY;
1108
                                                        dir[1].Attribute = ATTR_SUBDIRECTORY;
1099
                                                        dir[1].StartCluster = dircluster;
1109
                                                        dir[1].StartCluster = dircluster;
1100
                                                        dir[1].DateTime = 0;
1110
                                                        dir[1].DateTime = 0;
1101
                                                        dir[1].Size = 0;
1111
                                                        dir[1].Size = 0;
1102
                                                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// read in the sector.
1112
                                                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// read in the sector.
1103
                                                        {
1113
                                                        {
1104
                                                                Fat16_Deinit();
1114
                                                                Fat16_Deinit();
1105
                                                                return(retvalue);
1115
                                                                return(retvalue);
1106
                                                        }
1116
                                                        }
1107
                                                }
1117
                                                }
1108
                                                retvalue = 1;
1118
                                                retvalue = 1;
1109
                                                dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
1119
                                                dir_entry = DIRENTRIES_PER_SECTOR;      // stop for-loop
1110
                                        }
1120
                                        }
1111
                                }
1121
                                }
1112
                                dir_sector++; // search next sector
1122
                                dir_sector++; // search next sector
1113
                        // stop if we reached the end of the cluster or the end of the root dir
1123
                        // stop if we reached the end of the cluster or the end of the root dir
1114
                        }while((dir_sector < max_dir_sector) && (!retvalue));
1124
                        }while((dir_sector < max_dir_sector) && (!retvalue));
1115
 
1125
 
1116
                        // if we are seaching in the data area and the file not found in this cluster so take next cluster.
1126
                        // if we are seaching in the data area and the file not found in this cluster so take next cluster.
1117
                        if(!retvalue && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
1127
                        if(!retvalue && ( Partition.FirstDataSector <= file->FirstSectorOfCurrCluster))
1118
                        {
1128
                        {
1119
                                end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
1129
                                end_of_directory_not_reached = GetNextCluster(file);  // updates File->FirstSectorOfCurrCluster
1120
                        }
1130
                        }
1121
                }while((end_of_directory_not_reached) && (!retvalue));
1131
                }while((end_of_directory_not_reached) && (!retvalue));
1122
                // Perhaps we are at the end of the last cluster of a directory file an have no free direntry found.
1132
                // Perhaps we are at the end of the last cluster of a directory file an have no free direntry found.
1123
                // Then we would need to add a cluster to that file and create the new direntry there.
1133
                // Then we would need to add a cluster to that file and create the new direntry there.
1124
                // This code is not implemented yet, because its occurs only if more that 32*32=1024 direntries are
1134
                // This code is not implemented yet, because its occurs only if more that 32*32=1024 direntries are
1125
                // within a subdirectory of root.
1135
                // within a subdirectory of root.
1126
        }
1136
        }
1127
        return(retvalue);       // return 1 if file has been created otherwise return 0.
1137
        return(retvalue);       // return 1 if file has been created otherwise return 0.
1128
}
1138
}
1129
 
1139
 
1130
/********************************************************************************************************************************************/
1140
/********************************************************************************************************************************************/
1131
/*      Function:               FileExist(const int8_t* filename, uint8_t attribfilter, uint8_t attribmask, File_t *file);                                                                                      */
1141
/*      Function:               FileExist(const int8_t* filename, uint8_t attribfilter, uint8_t attribmask, File_t *file);                                                                                      */
1132
/*                                                                                                                                                                                                                                                                                      */
1142
/*                                                                                                                                                                                                                                                                                      */
1133
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1143
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1134
/*                                      in the rootdirectory of the drive. If the file is found the Filepointer properties are                                                                  */
1144
/*                                      in the rootdirectory of the drive. If the file is found the Filepointer properties are                                                                  */
1135
/*                                      updated.                                                                                                                                                                                                                                */
1145
/*                                      updated.                                                                                                                                                                                                                                */
1136
/*                                                                                                                                                                                                                                                                                      */
1146
/*                                                                                                                                                                                                                                                                                      */
1137
/*      Returnvalue:    1 if file is found else 0.                                                                                                                                                                                              */
1147
/*      Returnvalue:    1 if file is found else 0.                                                                                                                                                                                              */
1138
/********************************************************************************************************************************************/
1148
/********************************************************************************************************************************************/
1139
uint8_t FileExist(const int8_t* filename, const uint8_t attribfilter, const uint8_t attribmask, File_t *file)
1149
uint8_t FileExist(const int8_t* filename, const uint8_t attribfilter, const uint8_t attribmask, File_t *file)
1140
{
1150
{
1141
        int8_t* path = 0;
1151
        int8_t* path = 0;
1142
        int8_t* subpath = 0;
1152
        int8_t* subpath = 0;
1143
        uint8_t af, am, file_exist = 0;
1153
        uint8_t af, am, file_exist = 0;
1144
        int8_t  dirname[12]; // 8+3 + temination character
1154
        int8_t  dirname[12]; // 8+3 + temination character
1145
 
1155
 
1146
        // if incomming pointers are useless return immediatly
1156
        // if incomming pointers are useless return immediatly
1147
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1157
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1148
 
1158
 
1149
        // trace along the filepath
1159
        // trace along the filepath
1150
        path = (int8_t*)filename;                                                               // start a the beginning of the filename string
1160
        path = (int8_t*)filename;                                                               // start a the beginning of the filename string
1151
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
1161
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
1152
        file->DirectoryIndex = 0;
1162
        file->DirectoryIndex = 0;
1153
        // as long as the file was not found and the remaining path is not empty
1163
        // as long as the file was not found and the remaining path is not empty
1154
        while((*path != 0) && !file_exist)
1164
        while((*path != 0) && !file_exist)
1155
        {       // separate dirname and subpath from filepath string
1165
        {       // separate dirname and subpath from filepath string
1156
                subpath = SeperateDirName(path, dirname);
1166
                subpath = SeperateDirName(path, dirname);
1157
                if(subpath != NULL)
1167
                if(subpath != NULL)
1158
                {
1168
                {
1159
                        if(*subpath == 0)
1169
                        if(*subpath == 0)
1160
                        {       // empty subpath indicates last element of dir chain
1170
                        {       // empty subpath indicates last element of dir chain
1161
                                af = attribfilter;
1171
                                af = attribfilter;
1162
                                am = attribmask;
1172
                                am = attribmask;
1163
                        }
1173
                        }
1164
                        else  // it must be a subdirectory and no volume label
1174
                        else  // it must be a subdirectory and no volume label
1165
                        {
1175
                        {
1166
                                af = ATTR_SUBDIRECTORY;
1176
                                af = ATTR_SUBDIRECTORY;
1167
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
1177
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
1168
                        }
1178
                        }
1169
                        if(!DirectoryEntryExist(dirname, af, am, file))
1179
                        if(!DirectoryEntryExist(dirname, af, am, file))
1170
                        {
1180
                        {
1171
                                return (file_exist); // subdirectory does not exist
1181
                                return (file_exist); // subdirectory does not exist
1172
                        }
1182
                        }
1173
                        else
1183
                        else
1174
                        {
1184
                        {
1175
                                if (*subpath == 0)
1185
                                if (*subpath == 0)
1176
                                {
1186
                                {
1177
                                        file_exist = 1; // last element of path chain was found with the given attribute filter
1187
                                        file_exist = 1; // last element of path chain was found with the given attribute filter
1178
                                }
1188
                                }
1179
                        }
1189
                        }
1180
                }
1190
                }
1181
                else // error seperating the subpath
1191
                else // error seperating the subpath
1182
                {
1192
                {
1183
                        return file_exist; // bad subdir format
1193
                        return file_exist; // bad subdir format
1184
                }
1194
                }
1185
                path = subpath;
1195
                path = subpath;
1186
                subpath = 0;
1196
                subpath = 0;
1187
        }
1197
        }
1188
        return (file_exist);
1198
        return (file_exist);
1189
}
1199
}
1190
 
1200
 
1191
 
1201
 
1192
/********************************************************************************************************************************************/
1202
/********************************************************************************************************************************************/
1193
/*      Function:               FileCreate(const s8* filename, u8 attrib, File_t *file);                                                                                                                                */
1203
/*      Function:               FileCreate(const s8* filename, u8 attrib, File_t *file);                                                                                                                                */
1194
/*                                                                                                                                                                                                                                                                                      */
1204
/*                                                                                                                                                                                                                                                                                      */
1195
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1205
/*      Description:    This function looks for the specified file including its subdirectories beginning                                                                               */
1196
/*                                      in the rootdirectory of the partition. If the file is found the Filepointer properties are                                                              */
1206
/*                                      in the rootdirectory of the partition. If the file is found the Filepointer properties are                                                              */
1197
/*                                      updated. If file or its subdirectories are not found they will be created                                                                                               */
1207
/*                                      updated. If file or its subdirectories are not found they will be created                                                                                               */
1198
/*                                                                                                                                                                                                                                                                                      */
1208
/*                                                                                                                                                                                                                                                                                      */
1199
/*      Returnvalue:    1 if file was created else 0.                                                                                                                                                                                   */
1209
/*      Returnvalue:    1 if file was created else 0.                                                                                                                                                                                   */
1200
/********************************************************************************************************************************************/
1210
/********************************************************************************************************************************************/
1201
uint8_t FileCreate(const int8_t* filename, const uint8_t attrib, File_t *file)
1211
uint8_t FileCreate(const int8_t* filename, const uint8_t attrib, File_t *file)
1202
{
1212
{
1203
        int8_t *path = 0;
1213
        int8_t *path = 0;
1204
        int8_t *subpath = 0;
1214
        int8_t *subpath = 0;
1205
        uint8_t af, am, file_created = 0;
1215
        uint8_t af, am, file_created = 0;
1206
        int8_t dirname[12];
1216
        int8_t dirname[12];
1207
 
1217
 
1208
        // if incomming pointers are useless return immediatly
1218
        // if incomming pointers are useless return immediatly
1209
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1219
        if ((filename == NULL) || (file == NULL) || (!Partition.IsValid)) return 0;
1210
 
1220
 
1211
        // trace along the filepath
1221
        // trace along the filepath
1212
        path = (int8_t*)filename;                                                                       // start a the beginning of the filename string
1222
        path = (int8_t*)filename;                                                                       // start a the beginning of the filename string
1213
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
1223
        file->DirectorySector = 0;                                                              // start at RootDirectory with file search
1214
        file->DirectoryIndex = 0;
1224
        file->DirectoryIndex = 0;
1215
        // as long as the file was not created and the remaining file path is not empty
1225
        // as long as the file was not created and the remaining file path is not empty
1216
        while((*path != 0) && !file_created)
1226
        while((*path != 0) && !file_created)
1217
        {   // separate dirname and subpath from filepath string
1227
        {   // separate dirname and subpath from filepath string
1218
                subpath = SeperateDirName(path, dirname);
1228
                subpath = SeperateDirName(path, dirname);
1219
                if(subpath != NULL)
1229
                if(subpath != NULL)
1220
                {
1230
                {
1221
                        if(*subpath == 0)
1231
                        if(*subpath == 0)
1222
                        {       // empty subpath indicates last element of dir chain
1232
                        {       // empty subpath indicates last element of dir chain
1223
                                af = ATTR_NONE;
1233
                                af = ATTR_NONE;
1224
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;  // any file that is no subdir or volume label
1234
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;  // any file that is no subdir or volume label
1225
                        }
1235
                        }
1226
                        else  // it must be a subdirectory and no volume label
1236
                        else  // it must be a subdirectory and no volume label
1227
                        {
1237
                        {
1228
                                af = ATTR_SUBDIRECTORY;
1238
                                af = ATTR_SUBDIRECTORY;
1229
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
1239
                                am = ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL;
1230
                        }
1240
                        }
1231
                        if(!DirectoryEntryExist(dirname, af, am, file)) // if subdir or file is not existent
1241
                        if(!DirectoryEntryExist(dirname, af, am, file)) // if subdir or file is not existent
1232
                        {  // try to create subdir or file
1242
                        {  // try to create subdir or file
1233
                                if(*subpath == 0) af = attrib; // if last element in dir chain take the given attribute
1243
                                if(*subpath == 0) af = attrib; // if last element in dir chain take the given attribute
1234
                                if(!CreateDirectoryEntry(dirname, af, file))
1244
                                if(!CreateDirectoryEntry(dirname, af, file))
1235
                                {       // could not be created
1245
                                {       // could not be created
1236
                                        return(file_created);
1246
                                        return(file_created);
1237
                                }
1247
                                }
1238
                                else if (*subpath == 0) file_created = 1; // last element of path chain was created
1248
                                else if (*subpath == 0) file_created = 1; // last element of path chain was created
1239
                        }
1249
                        }
1240
                }
1250
                }
1241
                else // error seperating the subpath
1251
                else // error seperating the subpath
1242
                {
1252
                {
1243
                        return file_created; // bad subdir format
1253
                        return file_created; // bad subdir format
1244
                }
1254
                }
1245
                path = subpath;
1255
                path = subpath;
1246
                subpath = 0;
1256
                subpath = 0;
1247
        }
1257
        }
1248
        return (file_created);
1258
        return (file_created);
1249
}
1259
}
1250
 
1260
 
1251
 
1261
 
1252
/********************************************************************************************************************************************/
1262
/********************************************************************************************************************************************/
1253
/*      Function:               File_t * fopen_(int8_t* filename, int8_t mode);                                                                                                                                                                 */
1263
/*      Function:               File_t * fopen_(int8_t* filename, int8_t mode);                                                                                                                                                                 */
1254
/*                                                                                                                                                                                                                                                                                      */
1264
/*                                                                                                                                                                                                                                                                                      */
1255
/*      Description:    This function looks for the specified file in the rootdirectory of the drive. If the file is found the number of the    */
1265
/*      Description:    This function looks for the specified file in the rootdirectory of the drive. If the file is found the number of the    */
1256
/*                                      corrosponding filepointer is returned. Only modes 'r' (reading) and 'a' append are implemented yet.                                             */
1266
/*                                      corrosponding filepointer is returned. Only modes 'r' (reading) and 'a' append are implemented yet.                                             */
1257
/*                                                                                                                                                                                                                                                                                      */
1267
/*                                                                                                                                                                                                                                                                                      */
1258
/*      Returnvalue:    The filepointer to the file or 0 if faild.                                                                                                                                                              */
1268
/*      Returnvalue:    The filepointer to the file or 0 if faild.                                                                                                                                                              */
1259
/********************************************************************************************************************************************/
1269
/********************************************************************************************************************************************/
1260
File_t * fopen_(int8_t * const filename, const int8_t mode)
1270
File_t * fopen_(int8_t * const filename, const int8_t mode)
1261
{
1271
{
1262
        File_t *file    = 0;
1272
        File_t *file    = 0;
1263
 
1273
 
1264
        if((!Partition.IsValid) || (filename == 0)) return(file);
1274
        if((!Partition.IsValid) || (filename == 0)) return(file);
1265
 
1275
 
1266
        // Look for an unused filepointer in the file pointer list?
1276
        // Look for an unused filepointer in the file pointer list?
1267
        file = LockFilePointer();
1277
        file = LockFilePointer();
1268
        // if no unused file pointer was found return 0
1278
        // if no unused file pointer was found return 0
1269
        if(file == NULL) return(file);
1279
        if(file == NULL) return(file);
1270
 
1280
 
1271
        // now we have found a free filepointer and claimed it
1281
        // now we have found a free filepointer and claimed it
1272
        // so let initiate its property values
1282
        // so let initiate its property values
1273
        file->FirstSectorOfFirstCluster = 0;            // Sectorpointer to the first sector of the first datacluster of the file.
1283
        file->FirstSectorOfFirstCluster = 0;            // Sectorpointer to the first sector of the first datacluster of the file.
1274
        file->FirstSectorOfCurrCluster  = 0;            // Pointer to the cluster which is edited at the moment.
1284
        file->FirstSectorOfCurrCluster  = 0;            // Pointer to the cluster which is edited at the moment.
1275
        file->SectorOfCurrCluster               = 0;            // The sector which is edited at the moment (cluster_pointer + sector_index).
1285
        file->SectorOfCurrCluster               = 0;            // The sector which is edited at the moment (cluster_pointer + sector_index).
1276
        file->ByteOfCurrSector                  = 0;            // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
1286
        file->ByteOfCurrSector                  = 0;            // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index).
1277
        file->Mode                                              = mode;         // mode of fileoperation (read,write)
1287
        file->Mode                                              = mode;         // mode of fileoperation (read,write)
1278
        file->Size                                              = 0;            // the size of the opened file in bytes.
1288
        file->Size                                              = 0;            // the size of the opened file in bytes.
1279
        file->Position                                  = 0;            // pointer to a byte within the file 0 < fileposition < filesize
1289
        file->Position                                  = 0;            // pointer to a byte within the file 0 < fileposition < filesize
1280
        file->SectorInCache                             = 0;            // the last sector read, wich is still in the sectorbuffer.
1290
        file->SectorInCache                             = 0;            // the last sector read, wich is still in the sectorbuffer.
1281
        file->DirectorySector                   = 0;            // the sectorposition where the directoryentry has been made.
1291
        file->DirectorySector                   = 0;            // the sectorposition where the directoryentry has been made.
1282
        file->DirectoryIndex                    = 0;            // the index to the directoryentry within the specified sector.
1292
        file->DirectoryIndex                    = 0;            // the index to the directoryentry within the specified sector.
1283
        file->Attribute                                 = 0;            // the attribute of the file opened.
1293
        file->Attribute                                 = 0;            // the attribute of the file opened.
1284
 
1294
 
1285
        // check if a real file (no directory) to the given filename exist
1295
        // check if a real file (no directory) to the given filename exist
1286
        if(FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file))
1296
        if(FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file))
1287
        {  // file exist
1297
        {  // file exist
1288
                switch(mode)  // check mode
1298
                switch(mode)  // check mode
1289
                {
1299
                {
1290
                        case 'a':       // if mode is: append to file
1300
                        case 'a':       // if mode is: append to file
1291
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1301
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1292
                                {       // file is marked as readonly --> do not open this file
1302
                                {       // file is marked as readonly --> do not open this file
1293
                                        fclose_(file);
1303
                                        fclose_(file);
1294
                                        file = NULL;
1304
                                        file = NULL;
1295
                                }
1305
                                }
1296
                                else
1306
                                else
1297
                                {       // file is not marked as read only --> goto end of file
1307
                                {       // file is not marked as read only --> goto end of file
1298
                                        fseek_(file, 0, SEEK_END);              // point to the end of the file
1308
                                        fseek_(file, 0, SEEK_END);              // point to the end of the file
1299
                                }
1309
                                }
1300
                                break;
1310
                                break;
1301
                        case 'w':       // if mode is: write to file
1311
                        case 'w':       // if mode is: write to file
1302
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1312
                                if((file->Attribute & ATTR_READONLY) == ATTR_READONLY)
1303
                                {       // file is marked as readonly --> do not open this file
1313
                                {       // file is marked as readonly --> do not open this file
1304
                                        fclose_(file);
1314
                                        fclose_(file);
1305
                                        file = NULL;
1315
                                        file = NULL;
1306
                                }
1316
                                }
1307
                                else
1317
                                else
1308
                                {       // file is not marked as read only --> goto start of file
1318
                                {       // file is not marked as read only --> goto start of file
1309
                                        // free all clusters of that file
1319
                                        // free all clusters of that file
1310
                                        DeleteClusterChain(SectorToFat16Cluster(file->FirstSectorOfFirstCluster));
1320
                                        DeleteClusterChain(SectorToFat16Cluster(file->FirstSectorOfFirstCluster));
1311
                                        // mar an empy cluster as the last one and store the corresponding sector
1321
                                        // mar an empy cluster as the last one and store the corresponding sector
1312
                                        file->FirstSectorOfFirstCluster = Fat16ClusterToSector(FindNextFreeCluster(file));
1322
                                        file->FirstSectorOfFirstCluster = Fat16ClusterToSector(FindNextFreeCluster(file));
1313
                                        file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
1323
                                        file->FirstSectorOfCurrCluster = file->FirstSectorOfFirstCluster;
1314
                                        file->SectorOfCurrCluster = 0;
1324
                                        file->SectorOfCurrCluster = 0;
1315
                                        file->ByteOfCurrSector = 0;
1325
                                        file->ByteOfCurrSector = 0;
1316
                                        file->Size = 0;
1326
                                        file->Size = 0;
1317
                                        file->Position = 0;
1327
                                        file->Position = 0;
1318
                                        fseek_(file, 0, SEEK_SET);
1328
                                        fseek_(file, 0, SEEK_SET);
1319
                                }
1329
                                }
1320
                                break;
1330
                                break;
1321
                        case 'r':       // if mode is: read from file
1331
                        case 'r':       // if mode is: read from file
1322
                                // goto end of file
1332
                                // goto end of file
1323
                                fseek_(file, 0, SEEK_SET);
1333
                                fseek_(file, 0, SEEK_SET);
1324
                                break;
1334
                                break;
1325
                        default: // other modes are not supported
1335
                        default: // other modes are not supported
1326
                                fclose_(file);
1336
                                fclose_(file);
1327
                                file = NULL;
1337
                                file = NULL;
1328
                        break;
1338
                        break;
1329
                }
1339
                }
1330
                return(file);
1340
                return(file);
1331
        }
1341
        }
1332
        else // file does not exist
1342
        else // file does not exist
1333
        {
1343
        {
1334
                switch(mode)  // check mode
1344
                switch(mode)  // check mode
1335
                {
1345
                {
1336
                        case 'a':
1346
                        case 'a':
1337
                        case 'w': // if mode is write or append
1347
                        case 'w': // if mode is write or append
1338
                                // try to create the file
1348
                                // try to create the file
1339
                                if(!FileCreate(filename, ATTR_ARCHIVE, file))
1349
                                if(!FileCreate(filename, ATTR_ARCHIVE, file))
1340
                                { // if it could not be created
1350
                                { // if it could not be created
1341
                                        fclose_(file);
1351
                                        fclose_(file);
1342
                                        file = NULL;
1352
                                        file = NULL;
1343
                                }
1353
                                }
1344
                                break;
1354
                                break;
1345
                        case 'r': // else opened for 'r'
1355
                        case 'r': // else opened for 'r'
1346
                        default:  // of unsupported mode
1356
                        default:  // of unsupported mode
1347
                                fclose_(file);
1357
                                fclose_(file);
1348
                                file = NULL;
1358
                                file = NULL;
1349
                                break;
1359
                                break;
1350
                }
1360
                }
1351
                return(file);
1361
                return(file);
1352
        }
1362
        }
1353
        // we should never come to this point
1363
        // we should never come to this point
1354
        fclose_(file);
1364
        fclose_(file);
1355
        file = NULL;
1365
        file = NULL;
1356
        return(file);
1366
        return(file);
1357
}
1367
}
1358
 
1368
 
1359
/****************************************************************************************************************************************************/
1369
/****************************************************************************************************************************************************/
1360
/* Function:    fflush_(File *);                                                                                                                                                                                                                                        */
1370
/* Function:    fflush_(File *);                                                                                                                                                                                                                                        */
1361
/*                                                                                                                                                                                                                                                                                                      */
1371
/*                                                                                                                                                                                                                                                                                                      */
1362
/* Description: This function writes the data already in the buffer but not yet written to the file.                                                                                            */
1372
/* Description: This function writes the data already in the buffer but not yet written to the file.                                                                                            */
1363
/*                                                                                                                                                                                                                                                                                                      */
1373
/*                                                                                                                                                                                                                                                                                                      */
1364
/* Returnvalue: 0 on success EOF on error                                                                                                                                                                                                                       */
1374
/* Returnvalue: 0 on success EOF on error                                                                                                                                                                                                                       */
1365
/****************************************************************************************************************************************************/
1375
/****************************************************************************************************************************************************/
1366
int16_t fflush_(File_t * const file)
1376
int16_t fflush_(File_t * const file)
1367
{
1377
{
1368
        DirEntry_t *dir;
1378
        DirEntry_t *dir;
1369
 
1379
 
1370
        if((file == NULL) || (!Partition.IsValid)) return (EOF);
1380
        if((file == NULL) || (!Partition.IsValid)) return (EOF);
1371
 
1381
 
1372
        switch(file->Mode)
1382
        switch(file->Mode)
1373
        {
1383
        {
1374
                case 'a':
1384
                case 'a':
1375
                case 'w':
1385
                case 'w':
1376
                        if(file->ByteOfCurrSector > 0)                                                                          // has data been added to the file?
1386
                        if(file->ByteOfCurrSector > 0)                                                                          // has data been added to the file?
1377
                        {
1387
                        {
1378
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// save the data still in the buffer
1388
                                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))// save the data still in the buffer
1379
                                {
1389
                                {
1380
                                        Fat16_Deinit();
1390
                                        Fat16_Deinit();
1381
                                        return(EOF);
1391
                                        return(EOF);
1382
                                }
1392
                                }
1383
                        }
1393
                        }
1384
                        file->SectorInCache     = file->DirectorySector;
1394
                        file->SectorInCache     = file->DirectorySector;
1385
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))                                       // read the directory entry for this file.
1395
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))                                       // read the directory entry for this file.
1386
                        {
1396
                        {
1387
                                Fat16_Deinit();
1397
                                Fat16_Deinit();
1388
                                return(EOF);
1398
                                return(EOF);
1389
                        }
1399
                        }
1390
 
1400
 
1391
                        dir = (DirEntry_t *)file->Cache;
1401
                        dir = (DirEntry_t *)file->Cache;
1392
                        dir[file->DirectoryIndex].Size = file->Size;                                            // update file size
1402
                        dir[file->DirectoryIndex].Size = file->Size;                                            // update file size
1393
                        dir[file->DirectoryIndex].DateTime = FileDateTime(&SystemTime);         // update date time
1403
                        dir[file->DirectoryIndex].DateTime = FileDateTime(&SystemTime);         // update date time
1394
                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to sd-card
1404
                        if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))       // write back to sd-card
1395
                        {
1405
                        {
1396
                                Fat16_Deinit();
1406
                                Fat16_Deinit();
1397
                                return(EOF);
1407
                                return(EOF);
1398
                        }
1408
                        }
1399
                        break;
1409
                        break;
1400
                case 'r':
1410
                case 'r':
1401
                default:
1411
                default:
1402
                        return(EOF);
1412
                        return(EOF);
1403
                        break;
1413
                        break;
1404
 
1414
 
1405
        }
1415
        }
1406
        return(0);
1416
        return(0);
1407
}
1417
}
1408
 
1418
 
1409
/****************************************************************************************************************************************/
1419
/****************************************************************************************************************************************/
1410
/*      Function:               fclose_(File *file);                                                                                                                                                                                            */
1420
/*      Function:               fclose_(File *file);                                                                                                                                                                                            */
1411
/*                                                                                                                                                                                                                                                                              */
1421
/*                                                                                                                                                                                                                                                                              */
1412
/*      Description:    This function closes the open file by writing the remaining data                                                                                                        */
1422
/*      Description:    This function closes the open file by writing the remaining data                                                                                                        */
1413
/*                                      from the buffer to the device and entering the filesize in the directory entry.                                                                         */
1423
/*                                      from the buffer to the device and entering the filesize in the directory entry.                                                                         */
1414
/*                                                                                                                                                                                                                                                                              */
1424
/*                                                                                                                                                                                                                                                                              */
1415
/*      Returnvalue:    0 on success EOF on error                                                                                                                                                                                       */
1425
/*      Returnvalue:    0 on success EOF on error                                                                                                                                                                                       */
1416
/****************************************************************************************************************************************/
1426
/****************************************************************************************************************************************/
1417
int16_t fclose_(File_t *file)
1427
int16_t fclose_(File_t *file)
1418
{
1428
{
1419
        int16_t returnvalue = EOF;
1429
        int16_t returnvalue = EOF;
1420
 
1430
 
1421
        if(file == NULL) return(returnvalue);
1431
        if(file == NULL) return(returnvalue);
1422
        returnvalue = fflush_(file);
1432
        returnvalue = fflush_(file);
1423
        UnlockFilePointer(file);
1433
        UnlockFilePointer(file);
1424
        return(returnvalue);
1434
        return(returnvalue);
1425
}
1435
}
1426
 
1436
 
1427
/********************************************************************************************************************************************/
1437
/********************************************************************************************************************************************/
1428
/*      Function:               fgetc_(File *file);                                                                                                                                                                                                             */
1438
/*      Function:               fgetc_(File *file);                                                                                                                                                                                                             */
1429
/*                                                                                                                                                                                                                                                                                      */
1439
/*                                                                                                                                                                                                                                                                                      */
1430
/*      Description:    This function reads and returns one character from the specified file. Is the end of the actual sector reached the              */
1440
/*      Description:    This function reads and returns one character from the specified file. Is the end of the actual sector reached the              */
1431
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1441
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1432
/*                                                                                                                                                                                                                                                                                      */
1442
/*                                                                                                                                                                                                                                                                                      */
1433
/*      Returnvalue:    The function returns the character read from the specified memorylocation as u8 casted to s16 or EOF.                                   */
1443
/*      Returnvalue:    The function returns the character read from the specified memorylocation as u8 casted to s16 or EOF.                                   */
1434
/********************************************************************************************************************************************/
1444
/********************************************************************************************************************************************/
1435
int16_t fgetc_(File_t * const file)
1445
int16_t fgetc_(File_t * const file)
1436
{
1446
{
1437
        int16_t c = EOF;
1447
        int16_t c = EOF;
1438
        uint32_t curr_sector;
1448
        uint32_t curr_sector;
1439
 
1449
 
1440
        if( (!Partition.IsValid) || (file == NULL)) return(c);
1450
        if( (!Partition.IsValid) || (file == NULL)) return(c);
1441
        // if the end of the file is not reached, get the next character.
1451
        // if the end of the file is not reached, get the next character.
1442
        if((0 < file->Size) && ((file->Position+1) < file->Size) )
1452
        if((0 < file->Size) && ((file->Position+1) < file->Size) )
1443
        {
1453
        {
1444
                curr_sector  = file->FirstSectorOfCurrCluster;          // calculate the sector of the next character to be read.
1454
                curr_sector  = file->FirstSectorOfCurrCluster;          // calculate the sector of the next character to be read.
1445
                curr_sector += file->SectorOfCurrCluster;
1455
                curr_sector += file->SectorOfCurrCluster;
1446
 
1456
 
1447
                if(file->SectorInCache != curr_sector)
1457
                if(file->SectorInCache != curr_sector)
1448
                {
1458
                {
1449
                        file->SectorInCache = curr_sector;
1459
                        file->SectorInCache = curr_sector;
1450
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache,file->Cache))
1460
                        if(SD_SUCCESS != SDC_GetSector(file->SectorInCache,file->Cache))
1451
                        {
1461
                        {
1452
                                Fat16_Deinit();
1462
                                Fat16_Deinit();
1453
                                return(c);
1463
                                return(c);
1454
                        }
1464
                        }
1455
                }
1465
                }
1456
                c = (int16_t) file->Cache[file->ByteOfCurrSector];
1466
                c = (int16_t) file->Cache[file->ByteOfCurrSector];
1457
                file->Position++;                                                                       // increment file position
1467
                file->Position++;                                                                       // increment file position
1458
                file->ByteOfCurrSector++;                                                       // goto next byte in sector
1468
                file->ByteOfCurrSector++;                                                       // goto next byte in sector
1459
                if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if end of sector
1469
                if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if end of sector
1460
                {
1470
                {
1461
                        file->ByteOfCurrSector = 0;                                             //  reset byte location
1471
                        file->ByteOfCurrSector = 0;                                             //  reset byte location
1462
                        file->SectorOfCurrCluster++;                                    //      next sector
1472
                        file->SectorOfCurrCluster++;                                    //      next sector
1463
                        if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
1473
                        if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)    // if end of cluster is reached, the next datacluster has to be searched in the FAT.
1464
                        {
1474
                        {
1465
 
1475
 
1466
                                if(GetNextCluster(file))                                                                                // Sets the clusterpointer of the file to the next datacluster.
1476
                                if(GetNextCluster(file))                                                                                // Sets the clusterpointer of the file to the next datacluster.
1467
                                {
1477
                                {
1468
                                        file->SectorOfCurrCluster = 0;                                                          // start reading new cluster at first sector of the cluster.
1478
                                        file->SectorOfCurrCluster = 0;                                                          // start reading new cluster at first sector of the cluster.
1469
                                }
1479
                                }
1470
                                else // the last cluster was allready reached
1480
                                else // the last cluster was allready reached
1471
                                {
1481
                                {
1472
                                        file->SectorOfCurrCluster--;                                                    // jump back to the last sector in the last cluster
1482
                                        file->SectorOfCurrCluster--;                                                    // jump back to the last sector in the last cluster
1473
                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
1483
                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;                              // set ByteOfCurrSector one byte over sector end
1474
                                }
1484
                                }
1475
                        }
1485
                        }
1476
                }
1486
                }
1477
        }
1487
        }
1478
        return(c);
1488
        return(c);
1479
}
1489
}
1480
 
1490
 
1481
/********************************************************************************************************************************************/
1491
/********************************************************************************************************************************************/
1482
/*      Function:               fputc_( const s8 c, File *file);                                                                                                                                                                                */
1492
/*      Function:               fputc_( const s8 c, File *file);                                                                                                                                                                                */
1483
/*                                                                                                                                                                                                                                                                                      */
1493
/*                                                                                                                                                                                                                                                                                      */
1484
/*      Description:    This function writes a byte to the specified file and takes care of writing the necessary FAT- Entries.                                 */
1494
/*      Description:    This function writes a byte to the specified file and takes care of writing the necessary FAT- Entries.                                 */
1485
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1495
/*                                      next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT.    */
1486
/*                                                                                                                                                                                                                                                                                      */
1496
/*                                                                                                                                                                                                                                                                                      */
1487
/*      Returnvalue:    The function returns the character written to the stream or EOF on error.                                                                                               */
1497
/*      Returnvalue:    The function returns the character written to the stream or EOF on error.                                                                                               */
1488
/********************************************************************************************************************************************/
1498
/********************************************************************************************************************************************/
1489
int16_t fputc_(const int8_t c, File_t * const file)
1499
int16_t fputc_(const int8_t c, File_t * const file)
1490
{
1500
{
1491
        uint32_t curr_sector  = 0;
1501
        uint32_t curr_sector  = 0;
1492
 
1502
 
1493
        if((!Partition.IsValid) || (file == NULL)) return(EOF);
1503
        if((!Partition.IsValid) || (file == NULL)) return(EOF);
1494
 
1504
 
1495
        // If file position equals to file size, then the end of file has reached.
1505
        // If file position equals to file size, then the end of file has reached.
1496
        // In this chase it has to be checked that the ByteOfCurrSector is BYTES_PER_SECTOR
1506
        // In this chase it has to be checked that the ByteOfCurrSector is BYTES_PER_SECTOR
1497
        // and a new cluster should be appended.
1507
        // and a new cluster should be appended.
1498
        if((file->Position >= file->Size) && (file->ByteOfCurrSector >= BYTES_PER_SECTOR))
1508
        if((file->Position >= file->Size) && (file->ByteOfCurrSector >= BYTES_PER_SECTOR))
1499
        {
1509
        {
1500
                if(!AppendCluster(file)) return(EOF);
1510
                if(!AppendCluster(file)) return(EOF);
1501
        }
1511
        }
1502
 
1512
 
1503
        curr_sector  = file->FirstSectorOfCurrCluster;
1513
        curr_sector  = file->FirstSectorOfCurrCluster;
1504
        curr_sector += file->SectorOfCurrCluster;
1514
        curr_sector += file->SectorOfCurrCluster;
1505
        if(file->SectorInCache != curr_sector)
1515
        if(file->SectorInCache != curr_sector)
1506
        {
1516
        {
1507
                file->SectorInCache = curr_sector;
1517
                file->SectorInCache = curr_sector;
1508
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))
1518
                if(SD_SUCCESS != SDC_GetSector(file->SectorInCache, file->Cache))
1509
                {
1519
                {
1510
                        Fat16_Deinit();
1520
                        Fat16_Deinit();
1511
                        return(EOF);
1521
                        return(EOF);
1512
                }
1522
                }
1513
        }
1523
        }
1514
 
1524
 
1515
        file->Cache[file->ByteOfCurrSector] = (uint8_t)c;                       // write databyte into the buffer. The byte will be written to the device at once
1525
        file->Cache[file->ByteOfCurrSector] = (uint8_t)c;                       // write databyte into the buffer. The byte will be written to the device at once
1516
        if(file->Size == file->Position) file->Size++;          // a character has been written to the file so the size is incremented only when the character has been added at the end of the file.
1526
        if(file->Size == file->Position) file->Size++;          // a character has been written to the file so the size is incremented only when the character has been added at the end of the file.
1517
        file->Position++;                                                                       // the actual positon within the file.
1527
        file->Position++;                                                                       // the actual positon within the file.
1518
        file->ByteOfCurrSector++;                                                       // goto next byte in sector
1528
        file->ByteOfCurrSector++;                                                       // goto next byte in sector
1519
        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if the end of this sector is reached yet
1529
        if(file->ByteOfCurrSector >= BYTES_PER_SECTOR)          // if the end of this sector is reached yet
1520
        {       // save the sector to the sd-card
1530
        {       // save the sector to the sd-card
1521
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
1531
                if(SD_SUCCESS != SDC_PutSector(file->SectorInCache, file->Cache))
1522
                {
1532
                {
1523
                        Fat16_Deinit();
1533
                        Fat16_Deinit();
1524
                        return(EOF);
1534
                        return(EOF);
1525
                }
1535
                }
1526
                file->ByteOfCurrSector = 0;                                             //  reset byte location
1536
                file->ByteOfCurrSector = 0;                                             //  reset byte location
1527
                file->SectorOfCurrCluster++;                                    //      next sector
1537
                file->SectorOfCurrCluster++;                                    //      next sector
1528
                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)// if end of cluster is reached, the next datacluster has to be searched in the FAT.
1538
                if(file->SectorOfCurrCluster >= Partition.SectorsPerCluster)// if end of cluster is reached, the next datacluster has to be searched in the FAT.
1529
                {
1539
                {
1530
                        if(!GetNextCluster(file))                                                               // Sets the clusterpointer of the file to the next datacluster.
1540
                        if(!GetNextCluster(file))                                                               // Sets the clusterpointer of the file to the next datacluster.
1531
                        { // if current cluster was the last cluster of the file
1541
                        { // if current cluster was the last cluster of the file
1532
                                if(!AppendCluster(file))                                                // append a new and free cluster at the end of the file.
1542
                                if(!AppendCluster(file))                                                // append a new and free cluster at the end of the file.
1533
                                {
1543
                                {
1534
                                        file->SectorOfCurrCluster--;                            // jump back to last sector of last cluster
1544
                                        file->SectorOfCurrCluster--;                            // jump back to last sector of last cluster
1535
                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;      // set byte location to 1 byte over sector len
1545
                                        file->ByteOfCurrSector = BYTES_PER_SECTOR;      // set byte location to 1 byte over sector len
1536
                                        return(EOF);
1546
                                        return(EOF);
1537
                                }
1547
                                }
1538
                        }
1548
                        }
1539
                        else // next cluster
1549
                        else // next cluster
1540
                        {
1550
                        {
1541
                                file->SectorOfCurrCluster = 0;                                                  // start reading new cluster at first sector of the cluster.
1551
                                file->SectorOfCurrCluster = 0;                                                  // start reading new cluster at first sector of the cluster.
1542
                        }
1552
                        }
1543
                }
1553
                }
1544
        }
1554
        }
1545
        return(0);
1555
        return(0);
1546
}
1556
}
1547
 
1557
 
1548
 
1558
 
1549
/****************************************************************************************************************************************/
1559
/****************************************************************************************************************************************/
1550
/*      Function:               fread_(void *buffer, uint32_t size, uint32_t count, File *File);                                                                                                                                */
1560
/*      Function:               fread_(void *buffer, uint32_t size, uint32_t count, File *File);                                                                                                                                */
1551
/*                                                                                                                                                                                                                                                                              */
1561
/*                                                                                                                                                                                                                                                                              */
1552
/*      Description:    This function reads count objects of the specified size                                                                                                                         */
1562
/*      Description:    This function reads count objects of the specified size                                                                                                                         */
1553
/*                                      from the actual position of the file to the specified buffer.                                                                                                           */
1563
/*                                      from the actual position of the file to the specified buffer.                                                                                                           */
1554
/*                                                                                                                                                                                                                                                                              */
1564
/*                                                                                                                                                                                                                                                                              */
1555
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1565
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1556
/****************************************************************************************************************************************/
1566
/****************************************************************************************************************************************/
1557
uint32_t fread_(void * const buffer, uint32_t size, uint32_t count, File_t * const file)
1567
uint32_t fread_(void * const buffer, uint32_t size, uint32_t count, File_t * const file)
1558
{
1568
{
1559
        uint32_t object_cnt     = 0;                                                                                    // count the number of objects read from the file.
1569
        uint32_t object_cnt     = 0;                                                                                    // count the number of objects read from the file.
1560
        uint32_t object_size = 0;                                                                                       // count the number of bytes read from the actual object.
1570
        uint32_t object_size = 0;                                                                                       // count the number of bytes read from the actual object.
1561
        uint8_t *pbuff          = 0;                                                                                    // a pointer to the actual bufferposition.
1571
        uint8_t *pbuff          = 0;                                                                                    // a pointer to the actual bufferposition.
1562
        uint8_t success      = 1;                                                                                       // no error occured during read operation to the file.
1572
        uint8_t success      = 1;                                                                                       // no error occured during read operation to the file.
1563
        int16_t c;
1573
        int16_t c;
1564
 
1574
 
1565
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
1575
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
1566
 
1576
 
1567
        pbuff = (uint8_t *) buffer;                                                                                     // cast the void pointer to an u8 *
1577
        pbuff = (uint8_t *) buffer;                                                                                     // cast the void pointer to an u8 *
1568
 
1578
 
1569
        while((object_cnt < count) && success)
1579
        while((object_cnt < count) && success)
1570
        {
1580
        {
1571
                object_size = size;
1581
                object_size = size;
1572
                while((size > 0) && success)
1582
                while((size > 0) && success)
1573
                {
1583
                {
1574
                        c = fgetc_(file);
1584
                        c = fgetc_(file);
1575
                        if(c != EOF)
1585
                        if(c != EOF)
1576
                        {
1586
                        {
1577
                                *pbuff = (uint8_t)c;                                                                    // read a byte from the buffer to the opened file.
1587
                                *pbuff = (uint8_t)c;                                                                    // read a byte from the buffer to the opened file.
1578
                                pbuff++;
1588
                                pbuff++;
1579
                                size--;
1589
                                size--;
1580
                        }
1590
                        }
1581
                        else // error or end of file reached
1591
                        else // error or end of file reached
1582
                        {
1592
                        {
1583
                                success = 0;
1593
                                success = 0;
1584
                        }
1594
                        }
1585
                }
1595
                }
1586
                if(success) object_cnt++;
1596
                if(success) object_cnt++;
1587
        }
1597
        }
1588
        return(object_cnt);                                                                                             // return the number of objects succesfully read from the file
1598
        return(object_cnt);                                                                                             // return the number of objects succesfully read from the file
1589
}
1599
}
1590
 
1600
 
1591
 
1601
 
1592
/****************************************************************************************************************************************/
1602
/****************************************************************************************************************************************/
1593
/*      Function:               fwrite_(void *buffer, uint32_t size, uint32_t count, File *file);                                                                                                                               */
1603
/*      Function:               fwrite_(void *buffer, uint32_t size, uint32_t count, File *file);                                                                                                                               */
1594
/*                                                                                                                                                                                                                                                                              */
1604
/*                                                                                                                                                                                                                                                                              */
1595
/*      Description:    This function writes count objects of the specified size                                                                                                                        */
1605
/*      Description:    This function writes count objects of the specified size                                                                                                                        */
1596
/*                                      from the buffer pointer to the actual position in the file.                                                                                                                     */
1606
/*                                      from the buffer pointer to the actual position in the file.                                                                                                                     */
1597
/*                                                                                                                                                                                                                                                                              */
1607
/*                                                                                                                                                                                                                                                                              */
1598
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1608
/*      Returnvalue:    The function returns the number of objects (not bytes) read from the file.                                                                                      */
1599
/****************************************************************************************************************************************/
1609
/****************************************************************************************************************************************/
1600
uint32_t fwrite_(void * const buffer, uint32_t size, uint32_t count, File_t * const file)
1610
uint32_t fwrite_(void * const buffer, uint32_t size, uint32_t count, File_t * const file)
1601
{
1611
{
1602
        uint32_t object_cnt     = 0;                                                                                                            // count the number of objects written to the file.
1612
        uint32_t object_cnt     = 0;                                                                                                            // count the number of objects written to the file.
1603
        uint32_t object_size = 0;                                                                                                               // count the number of bytes written from the actual object.
1613
        uint32_t object_size = 0;                                                                                                               // count the number of bytes written from the actual object.
1604
        uint8_t *pbuff      = 0;                                                                                                                // a pointer to the actual bufferposition.
1614
        uint8_t *pbuff      = 0;                                                                                                                // a pointer to the actual bufferposition.
1605
        uint8_t success      = 1;                                                                                                               // no error occured during write operation to the file.
1615
        uint8_t success      = 1;                                                                                                               // no error occured during write operation to the file.
1606
        int16_t c;
1616
        int16_t c;
1607
 
1617
 
1608
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
1618
        if((!Partition.IsValid) || (file == NULL) || (buffer == NULL)) return(0);
1609
 
1619
 
1610
        pbuff = (uint8_t *) buffer;                                                                                                             // cast the void pointer to an u8 *
1620
        pbuff = (uint8_t *) buffer;                                                                                                             // cast the void pointer to an u8 *
1611
 
1621
 
1612
        while((object_cnt < count) && success)
1622
        while((object_cnt < count) && success)
1613
        {
1623
        {
1614
                object_size = size;
1624
                object_size = size;
1615
                while((size > 0) && success)
1625
                while((size > 0) && success)
1616
                {
1626
                {
1617
                        c = fputc_(*pbuff, file);                                                                               // write a byte from the buffer to the opened file.
1627
                        c = fputc_(*pbuff, file);                                                                               // write a byte from the buffer to the opened file.
1618
                        if(c != EOF)
1628
                        if(c != EOF)
1619
                        {
1629
                        {
1620
                                pbuff++;
1630
                                pbuff++;
1621
                                size--;
1631
                                size--;
1622
                        }
1632
                        }
1623
                        else
1633
                        else
1624
                        {
1634
                        {
1625
                                success = 0;
1635
                                success = 0;
1626
                        }
1636
                        }
1627
                }
1637
                }
1628
                if(success) object_cnt++;
1638
                if(success) object_cnt++;
1629
        }
1639
        }
1630
 
1640
 
1631
        return(object_cnt);                                                                                                                             // return the number of objects succesfully written to the file
1641
        return(object_cnt);                                                                                                                             // return the number of objects succesfully written to the file
1632
}
1642
}
1633
 
1643
 
1634
 
1644
 
1635
/****************************************************************************************************************************************/
1645
/****************************************************************************************************************************************/
1636
/*      Function:               fputs_(const int8_t *string, File_t *File);                                                                                                                                                             */
1646
/*      Function:               fputs_(const int8_t *string, File_t *File);                                                                                                                                                             */
1637
/*                                                                                                                                                                                                                                                                              */
1647
/*                                                                                                                                                                                                                                                                              */
1638
/*      Description:    This function writes a string to the specified file.                                                                                                                            */
1648
/*      Description:    This function writes a string to the specified file.                                                                                                                            */
1639
/*                                                                                                                                                                                                                                                                              */
1649
/*                                                                                                                                                                                                                                                                              */
1640
/*      Returnvalue:    The function returns a no negative value or EOF on error.                                                                                                                       */
1650
/*      Returnvalue:    The function returns a no negative value or EOF on error.                                                                                                                       */
1641
/****************************************************************************************************************************************/
1651
/****************************************************************************************************************************************/
1642
int16_t fputs_(int8_t * const string, File_t * const file)
1652
int16_t fputs_(int8_t * const string, File_t * const file)
1643
{
1653
{
1644
        uint8_t i=0;
1654
        uint8_t i=0;
1645
        int16_t c = 0;
1655
        int16_t c = 0;
1646
 
1656
 
1647
        if((!Partition.IsValid) || (file == NULL) || (string == NULL)) return(0);
1657
        if((!Partition.IsValid) || (file == NULL) || (string == NULL)) return(0);
1648
 
1658
 
1649
        while((string[i] != 0)&& (c != EOF))
1659
        while((string[i] != 0)&& (c != EOF))
1650
        {
1660
        {
1651
                c = fputc_(string[i], file);
1661
                c = fputc_(string[i], file);
1652
                i++;
1662
                i++;
1653
        }
1663
        }
1654
        return(c);
1664
        return(c);
1655
}
1665
}
1656
 
1666
 
1657
/****************************************************************************************************************************************/
1667
/****************************************************************************************************************************************/
1658
/*      Function:               fgets_(int8 *, int16_t , File_t *);                                                                                                                                                                             */
1668
/*      Function:               fgets_(int8 *, int16_t , File_t *);                                                                                                                                                                             */
1659
/*                                                                                                                                                                                                                                                                              */
1669
/*                                                                                                                                                                                                                                                                              */
1660
/*      Description:    This function reads a string from the file to the specifies string.                                                                                             */
1670
/*      Description:    This function reads a string from the file to the specifies string.                                                                                             */
1661
/*                                                                                                                                                                                                                                                                              */
1671
/*                                                                                                                                                                                                                                                                              */
1662
/*      Returnvalue:    A pointer to the string read from the file or 0 on error.                                                                                                                       */
1672
/*      Returnvalue:    A pointer to the string read from the file or 0 on error.                                                                                                                       */
1663
/****************************************************************************************************************************************/
1673
/****************************************************************************************************************************************/
1664
int8_t * fgets_(int8_t * const string, int16_t length, File_t * const file)
1674
int8_t * fgets_(int8_t * const string, int16_t length, File_t * const file)
1665
{
1675
{
1666
        int8_t *pbuff;
1676
        int8_t *pbuff;
1667
        int16_t c = 0, bytecount;
1677
        int16_t c = 0, bytecount;
1668
 
1678
 
1669
        if((!Partition.IsValid) || (file == NULL) || (string == NULL) || (length > 1)) return (0);
1679
        if((!Partition.IsValid) || (file == NULL) || (string == NULL) || (length > 1)) return (0);
1670
        pbuff = string;
1680
        pbuff = string;
1671
        bytecount = length;
1681
        bytecount = length;
1672
        while(bytecount > 1)                                                    // read the count-1 characters from the file to the string.
1682
        while(bytecount > 1)                                                    // read the count-1 characters from the file to the string.
1673
        {
1683
        {
1674
                c = fgetc_(file);                                                       // read a character from the opened file.
1684
                c = fgetc_(file);                                                       // read a character from the opened file.
1675
                switch(c)
1685
                switch(c)
1676
                {
1686
                {
1677
                        case 0x0A:
1687
                        case 0x0A:
1678
                                *pbuff = 0;                                                     // set string terminator
1688
                                *pbuff = 0;                                                     // set string terminator
1679
                                return(string);                                         // stop loop
1689
                                return(string);                                         // stop loop
1680
                                break;
1690
                                break;
1681
 
1691
 
1682
                        case EOF:
1692
                        case EOF:
1683
                                *pbuff = 0;                                                     // set string terminator
1693
                                *pbuff = 0;                                                     // set string terminator
1684
                                return(0);
1694
                                return(0);
1685
                        default:
1695
                        default:
1686
                                *pbuff++ = (int8_t)c;                           // copy byte to string
1696
                                *pbuff++ = (int8_t)c;                           // copy byte to string
1687
                                bytecount--;
1697
                                bytecount--;
1688
                                break;
1698
                                break;
1689
                }
1699
                }
1690
        }
1700
        }
1691
        *pbuff = 0;
1701
        *pbuff = 0;
1692
        return(string);
1702
        return(string);
1693
}
1703
}
1694
 
1704
 
1695
/****************************************************************************************************************************************/
1705
/****************************************************************************************************************************************/
1696
/*      Function:               fexist_(const int8_t*);                                                                                                                                                                                                 */
1706
/*      Function:               fexist_(const int8_t*);                                                                                                                                                                                                 */
1697
/*                                                                                                                                                                                                                                                                              */
1707
/*                                                                                                                                                                                                                                                                              */
1698
/*      Description:    This function checks if a file already exist.                                                                                                                                           */
1708
/*      Description:    This function checks if a file already exist.                                                                                                                                           */
1699
/*                                                                                                                                                                                                                                                                              */
1709
/*                                                                                                                                                                                                                                                                              */
1700
/*      Returnvalue:    1 if the file exist else 0.                                                                                                                                                                                     */
1710
/*      Returnvalue:    1 if the file exist else 0.                                                                                                                                                                                     */
1701
/****************************************************************************************************************************************/
1711
/****************************************************************************************************************************************/
1702
uint8_t fexist_(int8_t* const filename)
1712
uint8_t fexist_(int8_t* const filename)
1703
{
1713
{
1704
        uint8_t exist = 0;
1714
        uint8_t exist = 0;
1705
        File_t *file = 0;
1715
        File_t *file = 0;
1706
        file = LockFilePointer();
1716
        file = LockFilePointer();
1707
        exist = FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file);
1717
        exist = FileExist(filename, ATTR_NONE, ATTR_SUBDIRECTORY|ATTR_VOLUMELABEL, file);
1708
        UnlockFilePointer(file);
1718
        UnlockFilePointer(file);
1709
        return(exist);
1719
        return(exist);
1710
}
1720
}
1711
 
1721
 
1712
/****************************************************************************************************************************************/
1722
/****************************************************************************************************************************************/
1713
/*      Function:               feof_(File_t *File);                                                                                                                                                                                            */
1723
/*      Function:               feof_(File_t *File);                                                                                                                                                                                            */
1714
/*                                                                                                                                                                                                                                                                              */
1724
/*                                                                                                                                                                                                                                                                              */
1715
/*      Description:    This function checks wether the end of the file has been reached.                                                                                                                                               */
1725
/*      Description:    This function checks wether the end of the file has been reached.                                                                                                                                               */
1716
/*                                                                                                                                                                                                                                                                              */
1726
/*                                                                                                                                                                                                                                                                              */
1717
/*      Returnvalue:    0 if the end of the file was not reached otherwise 1.                                                                                                                                                                           */
1727
/*      Returnvalue:    0 if the end of the file was not reached otherwise 1.                                                                                                                                                                           */
1718
/****************************************************************************************************************************************/
1728
/****************************************************************************************************************************************/
1719
uint8_t feof_(File_t *file)
1729
uint8_t feof_(File_t *file)
1720
{
1730
{
1721
        if(((file->Position)+1) < (file->Size))
1731
        if(((file->Position)+1) < (file->Size))
1722
        {
1732
        {
1723
                return(0);
1733
                return(0);
1724
        }
1734
        }
1725
        else
1735
        else
1726
        {
1736
        {
1727
                return(1);
1737
                return(1);
1728
        }
1738
        }
1729
}
1739
}
1730
 
1740
 
1731
 
1741
 
1732
 
1742