54,7 → 54,7 |
// + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// + POSSIBILITY OF SUCH DAMAGE. |
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
#include <stdio.h> |
//#include <stdio.h> |
#include "91x_lib.h" |
#include "fat16.h" |
#include "sdc.h" |
64,25 → 64,27 |
//________________________________________________________________________________________________________________________________________ |
// Module name: fat16.c |
// Compiler used: avr-gcc 3.4.5 |
// Last Modifikation: 24.07.2007 |
// Version: 1.24 |
// Authors: Stephan Busker |
// Description: Source files for FAT16 implementation with read and write-access using AVR-Mikrocontrollers |
// Copyright (C) 2007 Stephan Busker |
// Last Modifikation: 16.06.2008 |
// Version: 2.00 |
// Authors: Stephan Busker & Gregor Stobrawa |
// Description: Source files for FAT16 implementation with read and write-access |
// Copyright (C) 2008 Stephan Busker & Gregor Stobrawa |
//........................................................................................................................................ |
// Functions: extern u8 InitFat16(void); |
// u8 fopen_(u8 *fname,s8 mode, File *file); |
// void fclose_(File *file); |
// u32 fread_(void *buffer, u32 size, u32 count, File *file); |
// u32 fwrite_(void *buffer, u32 size, u32 count, File *file); |
// s16 fseek_(File *file, s32 offset, s16 origin); |
// s8 fgets8_(File *file); |
// u8 fputchar_(File *file,s8 c); |
// u8 fputs_(File *file,s8 *string); |
// s8 * fgets(s8 *, s16, File); |
// u8 fexist_(u8*, File *file); |
// Functions: extern s16 Fat16_Init(void); |
// extern s16 Fat16_Deinit(void); |
// extern File_t * fopen_(const u8 *filename, const s8 mode); |
// extern s16 fclose_(File_t *File); |
// extern s16 fflush_(File_t *File); |
// extern s16 fseek_(File_t *File, s32 offset, s16 origin); |
// extern s16 fgetc_(File_t *File); |
// extern s16 fputc_(u8 c, File_t *File); |
// extern u32 fread_(void *buffer, u32 size, u32 count, File_t *File); |
// extern u32 fwrite_(void *buffer, u32 size, u32 count, File_t *File); |
// extern s16 fputs_(const u8 *string, File_t *File); |
// extern u8 * fgets_(u8 *string, s16 length, File_t *File); |
//........................................................................................................................................ |
// ext. functions: extern SD_Result_t SDC_Init(void;) |
// extern SD_Result_t SDC_Deinit(void); |
// extern SD_Result_t SDC_GetSector (u32,u8 *); |
// extern SD_Result_t SDC_PutSector (u32,u8 *); |
//........................................................................................................................................ |
98,7 → 100,6 |
Fat Tables Start + # of Reserved Sectors |
Root Directory Entry Start + # of Reserved + (# of Sectors Per FAT * 2) |
Data Area (Starts with Cluster #2) Start + # of Reserved + (# of Sectors Per FAT * 2) + ((Maximum Root Directory Entries * 32) / Bytes per Sector) |
|
*/ |
|
|
130,18 → 131,26 |
*/ |
|
// Partition Types: |
#define P_TYPE_UNKNOWN 0x00 |
#define P_TYPE_FAT12 0x01 |
#define P_TYPE_FAT16_SM16MB 0x04 |
#define P_TYPE_EXTMSDOS 0x05 |
#define P_TYPE_FAT16 0x06 |
#define P_TYPE_FAT32 0x0B |
#define P_TYPE_FAT32_LBA1 0x0C |
#define P_TYPE_FAT16_LBA1 0x0E |
#define P_TYPE_EXTMSDOS_LBA1 0x0F |
#define PART_TYPE_UNKNOWN 0x00 |
#define PART_TYPE_FAT12 0x01 |
#define PART_TYPE_XENIX 0x02 |
#define PART_TYPE_DOSFAT16 0x04 |
#define PART_TYPE_EXTDOS 0x05 |
#define PART_TYPE_FAT16 0x06 |
#define PART_TYPE_NTFS 0x07 |
#define PART_TYPE_FAT32 0x0B |
#define PART_TYPE_FAT32LBA 0x0C |
#define PART_TYPE_FAT16LBA 0x0E |
#define PART_TYPE_EXTDOSLBA 0x0F |
#define PART_TYPE_ONTRACK 0x33 |
#define PART_TYPE_NOVELL 0x40 |
#define PART_TYPE_PCIX 0x4B |
#define PART_TYPE_PHOENIXSAVE 0xA0 |
#define PART_TYPE_CPM 0xDB |
#define PART_TYPE_DBFS 0xE0 |
#define PART_TYPE_BBT 0xFF |
|
|
|
/* |
________________________________________________________________________________________________________________________________________ |
|
198,6 → 207,7 |
} __attribute__((packed)) VBR_Entry_t; |
|
|
|
/* |
________________________________________________________________________________________________________________________________________ |
|
208,38 → 218,52 |
*/ |
typedef struct |
{ |
u8 name[8]; // 8 bytes name. |
u8 extension[3]; // 3 bytes extension. |
u8 attribute; // attribute of the directory entry (unused,archive,read-only,system,directory,volume) |
u8 reserved[10]; // reserved bytes within the directory entry. |
u16 time; // time and |
u16 date; // date of last write acces to the file or directory. |
u16 startcluster; // first cluster of the file or directory. |
u32 size; // size of the file or directory in bytes. |
u8 Name[8]; // 8 bytes name, padded with spaces. |
u8 Extension[3]; // 3 bytes extension, padded with spaces. |
u8 Attribute; // attribute of the directory entry (unused,archive,read-only,system,directory,volume) |
u8 Reserved[10]; // reserved bytes within the directory entry. |
u16 Time; // time and |
u16 Date; // date of last write acces to the file or directory. |
u16 StartCluster; // first cluster of the file or directory. |
u32 Size; // size of the file or directory in bytes. |
} __attribute__((packed)) DirEntry_t; |
|
#define SLOT_EMPTY 0x00 // slot has never been used |
#define SLOT_E5 0x05 // the real value is 0xe5 |
#define SLOT_DELETED 0xe5 // file in this slot deleted |
|
#define ATTR_NORMAL 0x00 // normal file |
#define ATTR_READONLY 0x01 // file is readonly |
#define ATTR_HIDDEN 0x02 // file is hidden |
#define ATTR_SYSTEM 0x04 // file is a system file |
#define ATTR_VOLUMELABEL 0x08 // entry is a volume label |
#define ATTR_LONG_FILENAME 0x0F // this is a long filename entry |
#define ATTR_SUBDIRECTORY 0x10 // entry is a directory name |
#define ATTR_ARCHIVE 0x20 // file is new or modified |
|
|
/* |
________________________________________________________________________________________________________________________________________ |
|
Structure of an entry within the fileallocationtable. |
________________________________________________________________________________________________________________________________________ |
|
0000h Available Cluster |
0002h-FFEFh Used, Next Cluster in File |
FFF0h-FFF6h Reserved Cluster |
FFF7h BAD Cluster |
FFF8h-FFFF Used, Last Cluster in File |
*/ |
typedef struct |
{ |
u16 next_cluster; // the next cluster of the file. |
} __attribute__((packed)) FatEntry_t; |
u16 NextCluster; // the next cluster of the file. |
} __attribute__((packed)) Fat16Entry_t; |
|
// secial fat entries |
#define FAT16_CLUSTER_FREE 0x0000 |
#define FAT16_CLUSTER_RESERVED 0x0001 |
#define FAT16_CLUSTER_USED_MIN 0x0002 |
#define FAT16_CLUSTER_USED_MAX 0xFFEF |
#define FAT16_CLUSTER_ROOTDIR_MIN 0xFFF0 |
#define FAT16_CLUSTER_ROOTDIR_MAX 0xFFF6 |
#define FAT16_CLUSTER_BAD 0xFFF7 |
#define FAT16_CLUSTER_LAST_MIN 0xFFF8 |
#define FAT16_CLUSTER_LAST_MAX 0xFFFF |
|
|
#define MBR_SECTOR 0x00 // the masterboot record is located in sector 0. |
|
|
/*****************************************************************************************************************************************/ |
/* */ |
/* Global variables needed for read- or write-acces to the FAT16- filesystem. */ |
246,51 → 270,151 |
/* */ |
/*****************************************************************************************************************************************/ |
|
u8 SectorsPerCluster = 0; // how many sectors does a cluster contain? |
u8 FatCopies = 0; // Numbers of copies of the FAT |
u16 PossibleRootEntries = 0; // Possible number of entries in the root directory. |
u16 SectorsPerFat = 0; // how many sectors does a fat16 contain? |
u32 ReservedSectors = 0; // Sectors reserved by the filesystem. |
u32 FirstPartitionSector = 0; // Distance in sectors between the first partition and the master bootrecord. |
u32 FileAllocationTable = 0; // pointer to the first FAT |
u32 RootDirectory = 0; // Pointer to the rootdirectory of the first partition. |
u32 FirstDataCluster = 0; // Pointer to the first cluster containing data (cluster0). |
#define MBR_SECTOR 0x00 // the masterboot record is located in sector 0. |
#define DIRENTRY_SIZE 32 //bytes |
#define DIRENTRIES_PER_SECTOR BYTES_PER_SECTOR/DIRENTRY_SIZE |
#define FAT16_BYTES 2 |
#define FAT16_ENTRIES_PER_SECTOR BYTES_PER_SECTOR/FAT16_BYTES |
|
DirEntry_t *DirectoryEntry; // Pointer to an entry of the directory. |
FatEntry_t *Fat; // Pointer to an entry of the fat (next clusterposition). |
#define FSTATE_UNUSED 0 |
#define FSTATE_USED 1 |
|
File_t FilePointer[__MAX_FILES_USED]; // Allocate Memmoryspace for each filepointer used. |
typedef struct |
{ |
u8 IsValid; // 0 means invalid, else valid |
u8 SectorsPerCluster; // how many sectors does a cluster contain? |
u8 FatCopies; // Numbers of copies of the FAT |
u16 MaxRootEntries; // Possible number of entries in the root directory. |
u16 SectorsPerFat; // how many sectors does a fat16 contain? |
u32 FirstFatSector; // sector of the start of the fat |
u32 FirstRootDirSector; // sector of the rootdirectory |
u32 FirstDataSector; // sector of the first cluster containing data (cluster2). |
} Partition_t; |
|
Partition_t Partition; // Structure holds partition information |
|
/***************************************************************************************************************************************/ |
/* Function: InitFat16(void); */ |
/* */ |
/* Description: This function reads the Masterbootrecord and finds the position of the Volumebootrecord, the FAT and the Rootdir */ |
/* and stores the information in global variables. */ |
/* */ |
/* Returnvalue: The function returns "0" if the filesystem is initialized. */ |
/***************************************************************************************************************************************/ |
u8 InitFat16(void) |
File_t FilePointer[FILE_MAX_OPEN]; // Allocate Memmoryspace for each filepointer used. |
|
/****************************************************************************************************************************************/ |
/* Function: SeperateDirName(u8*, u8*, u8*); */ |
/* */ |
/* Description: This function seperates the first dirname from filepath and brings them */ |
/* into the needed format ('test.txt' -> 'TEST TXT') */ |
/* The subpath is the pointer to the remaining substring if the filepath */ |
/* */ |
/* Returnvalue: Return 0 on error */ |
/****************************************************************************************************************************************/ |
u8 SeperateDirName(const u8 *filepath, u8 *dirname, u8 *subpath) |
{ |
u8* readpointer = 0; |
u8 writepointer = 0; |
|
// search subpath from beginning of filepath |
subpath = 0; |
readpointer = (u8*)filepath; |
if(*readpointer == '/') readpointer++; // ignore first '/' |
while(!subpath) // search the filepath until a subpath was found. |
{ |
if(((*readpointer == 0) || (*readpointer == '/'))) // if '/' found or end of filepath reached |
{ |
subpath = readpointer; // store the position of the first "/" found after the beginning of the filenpath |
} |
readpointer++; |
} |
|
// clear dirname with spaces |
for(writepointer = 0; writepointer < 11; writepointer++) dirname[writepointer] = ' '; |
writepointer = 0; |
// start seperating the dirname from the filepath. |
readpointer = (u8*)filepath; |
if(*readpointer == '/') readpointer++; // ignore first '/' |
while( readpointer < subpath) |
{ |
if(writepointer >= 11) return 0; // dirname to long |
if(*readpointer == '.') // seperating dirname and extension. |
{ |
if(writepointer<8) |
{ |
readpointer++; // next character in filename |
writepointer = 8; // jump to start of extension |
} |
else return (0); // dirbasename to long |
} |
else |
{ |
if((0x60 < *readpointer) && (*readpointer < 0x7B)) |
{ |
dirname[writepointer] = (*readpointer - 0x20); // all characters must be upper case. |
} |
else |
{ |
dirname[writepointer] = *readpointer; |
} |
readpointer++; |
writepointer++; |
} |
} |
return (1); |
} |
|
|
/**************************************************************************************************************************************+*/ |
/* Function: Fat16ClusterToSector( u16 cluster); */ |
/* */ |
/* Description: This function converts a cluster number given by the fat to the corresponding */ |
/* sector that points to the start of the data area that is represented by the cluster number. */ |
/* */ |
/* Returnvalue: The sector number with the data area of the given cluster */ |
/****************************************************************************************************************************************/ |
u32 Fat16ClusterToSector(u16 cluster) |
{ |
if (cluster < 2) cluster = 2; // the 0. and 1. cluster in the fat are used for the media descriptor |
return ( (cluster - 2) * Partition.SectorsPerCluster) + Partition.FirstDataSector; // the first data sector is represented by the 2nd cluster |
} |
|
/****************************************************************************************************************************************/ |
/* Function: SectorToFat16Cluster( u32 sector); */ |
/* */ |
/* Description: This function converts a given sector number given to the corresponding */ |
/* cluster number in the fat that represents this data area. */ |
/* */ |
/* Returnvalue: The cluster number representing the data area of the sector. */ |
/****************************************************************************************************************************************/ |
u16 SectorToFat16Cluster(u32 sector) |
{ |
return ((u16)((sector - Partition.FirstDataSector) / Partition.SectorsPerCluster) + 2); |
} |
|
/****************************************************************************************************************************************/ |
/* Function: Fat16_Init(void); */ |
/* */ |
/* Description: This function reads the Masterbootrecord and finds the position of the Volumebootrecord, the FAT and the Rootdir */ |
/* and stores the information in global variables. */ |
/* */ |
/* Returnvalue: The function returns "0" if the filesystem is initialized. */ |
/****************************************************************************************************************************************/ |
s16 InitFat16_Init(void) |
{ |
u8 cnt = 0; |
SD_Result_t sdresult = SD_ERROR_UNKNOWN; |
VBR_Entry_t *VBR; // Pointer to the VolumeBootRecord. |
MBR_Entry_t *MBR; // Pointer to the masterbootrecord. |
File_t *file; |
u32 PartitionFirstSector; |
VBR_Entry_t *VBR; |
MBR_Entry_t *MBR; |
File_t *File; |
|
Partition.IsValid = 0; |
|
// declare the filepointers as unused. |
for(cnt=0;cnt<__MAX_FILES_USED;cnt++) |
for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++) |
{ |
FilePointer[cnt].state = _UNUSED; |
FilePointer[cnt].State = FSTATE_UNUSED; |
} |
// set current file pinter to first position in list |
file = &FilePointer[0]; |
File = &FilePointer[0]; |
|
// try to initialise the sd-card. |
cnt = 0; |
do |
while(SD_SUCCESS != SDC_Init()) |
{ |
sdresult = SDC_Init(); |
if(cnt > 200) |
{ |
SerialPutString("SD-Card could not be initialized.\r\n"); |
297,52 → 421,49 |
return(1); |
} |
cnt++; |
}while(sdresult != SD_SUCCESS); |
} |
|
// SD-Card is initialized successfully |
sdresult = SDC_GetSector((u32)MBR_SECTOR,file->buffer); // Read the MasterBootRecord |
if(sdresult != SD_SUCCESS) |
if(SD_SUCCESS != SDC_GetSector((u32)MBR_SECTOR,File->Cache)) // Read the MasterBootRecord |
{ |
SerialPutString("Error reading the MBR.\r\n"); |
return(2); |
} |
MBR = (MBR_Entry_t *) file->buffer; // Enter the MBR using the structure MBR_Entry_t. |
if(MBR->PartitionEntry1.Type != P_TYPE_FAT16) |
MBR = (MBR_Entry_t *)File->Cache; // Enter the MBR using the structure MBR_Entry_t. |
if(MBR->PartitionEntry1.Type != PART_TYPE_FAT16) |
{ |
SerialPutString("MBR: 1st Partition ist not FAT16 type.\r\n"); |
return(1); |
} |
// get sector offset 1st partition |
FirstPartitionSector = MBR->PartitionEntry1.NoSectorsBeforePartition; |
PartitionFirstSector = MBR->PartitionEntry1.NoSectorsBeforePartition; |
// Start of Partition is the Volume Boot Sector |
sdresult = SDC_GetSector(FirstPartitionSector,file->buffer); // Read the volume boot record |
if(sdresult != SD_SUCCESS) |
if(SD_SUCCESS != SDC_GetSector(PartitionFirstSector,File->Cache)) // Read the volume boot record |
{ |
SerialPutString("Error reading the VBR of 1st partition.\r\n"); |
return(2); |
} |
VBR = (VBR_Entry_t *) file->buffer; // Enter the VBR using the structure VBR_Entry_t. |
if(VBR->BytesPerSector != 512) |
VBR = (VBR_Entry_t *) File->Cache; // Enter the VBR using the structure VBR_Entry_t. |
if(VBR->BytesPerSector != BYTES_PER_SECTOR) |
{ |
SerialPutString("Sector size of 1st partition not supported.\r\n"); |
return(3); |
} |
SectorsPerCluster = VBR->SectorsPerCluster; // Number of sectors per cluster. Depends on the memorysize of the sd-card. |
FatCopies = VBR->NoFATCopies; // Number of fatcopies. |
PossibleRootEntries = VBR->MaxRootEntries; // How many Entries are possible in the rootdirectory (FAT16 allows max. 512 entries). |
SectorsPerFat = VBR->SectorsPerFAT; // The number of sectors per FAT. |
ReservedSectors = VBR->ReservedSectors; // The number of sectors that are reserved |
Partition.SectorsPerCluster = VBR->SectorsPerCluster; // Number of sectors per cluster. Depends on the memorysize of the sd-card. |
Partition.FatCopies = VBR->NoFATCopies; // Number of fatcopies. |
Partition.MaxRootEntries = VBR->MaxRootEntries; // How many Entries are possible in the rootdirectory (FAT16 allows max. 512 entries). |
Partition.SectorsPerFat = VBR->SectorsPerFAT; // The number of sectors per FAT. |
|
/* Calculate the sectorpositon of the FAT, the Rootdirectory and the first Datacluster. */ |
// Calculate the position of the FileAllocationTable: |
// Start + # of Reserved Sectors |
FileAllocationTable = (u32)(FirstPartitionSector + (u32)ReservedSectors); |
Partition.FirstFatSector = (u32)(PartitionFirstSector + (u32)(VBR->ReservedSectors)); |
// Calculate the position of the Rootdirectory: |
// Start + # of Reserved Sectors + (# of Sectors Per FAT * # of FAT Copies) |
RootDirectory = (u32)((u32)FileAllocationTable + (u32)((u32)SectorsPerFat*(u32)FatCopies)); |
Partition.FirstRootDirSector = Partition.FirstFatSector + (u32)((u32)Partition.SectorsPerFat*(u32)Partition.FatCopies); |
// Calculate the position of the first datacluster: |
// Start + # of Reserved + (# of Sectors Per FAT * # of FAT Copies) + ((Maximum Root Directory Entries * 32) / Bytes per Sector) |
FirstDataCluster = (u32)((u32)RootDirectory + ((u32)(PossibleRootEntries>>4))); // assuming 512 Byte Per Sector |
Partition.FirstDataSector = Partition.FirstRootDirSector + (u32)(Partition.MaxRootEntries>>4); // assuming 512 Byte Per Sector |
// check for FAT16 in VBR of first partition |
if(!((VBR->FATName[0]=='F') && (VBR->FATName[1]=='A') && (VBR->FATName[2]=='T') && (VBR->FATName[3]=='1')&&(VBR->FATName[4]=='6'))) |
{ |
349,854 → 470,869 |
SerialPutString("VBR: Partition ist not FAT16 type.\r\n"); |
return (2); |
} |
Partition.IsValid = 1; // mark data in partition structure as valid |
return(0); |
} |
|
/****************************************************************************************************************************************************/ |
/* Function: u16 SeekDirectoryEntry(u8*, File *) */ |
/* */ |
/* Description: this function searches all possible rootentries until the file or directory is found or the end of the rootdirectory is reached */ |
/* */ |
/* Returnvalue: This function returns 1 if the directoryentry specified was found. */ |
/****************************************************************************************************************************************************/ |
u8 SeekDirectoryEntry(u8 *fname, File_t *file) |
/****************************************************************************************************************************************/ |
/* Function: Fat16_Deinit(void); */ |
/* */ |
/* Description: This function uninitializes the fat 16 api */ |
/* */ |
/* Returnvalue: The function returns "0" on success */ |
/****************************************************************************************************************************************/ |
s16 Fat16_Deinit(void) |
{ |
u16 rootentry = 0; |
u16 end_of_directory_not_reached = 0; // the directory has been read completely without a result. |
u8 i = 0; |
u8 retvalue = 0; |
u32 cluster_temp = 0; |
u16 cnt = 0; |
|
// directory starts at sector specified by dir_sector. This can be the rootdirectory or any other directory. |
do |
{ // search the next 16 rootentries in this sector of the roordirectory. |
rootentry = 0; |
SDC_GetSector((u32) file->cluster_pointer,file->buffer); // Read the Rootdirectory. |
DirectoryEntry = (DirEntry_t *)file->buffer; |
|
while( (!retvalue) && (rootentry<16) ) |
s16 returnvalue = 0; |
u8 cnt; |
// declare the filepointers as unused. |
for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++) |
{ |
if(FilePointer[cnt].State == FSTATE_USED) |
{ |
cnt++; |
|
// compare the dirnames (8+3 = ) |
i = 0; |
while((i < 10) && (DirectoryEntry[rootentry].name[i] == fname[i])) |
{ |
i++; |
} |
if((i==10) && (DirectoryEntry[rootentry].attribute == file->attribute)) // entry found!! -> reading startcluster of entry from offset 26. |
{ |
cluster_temp = (u32)DirectoryEntry[rootentry].startcluster; |
cluster_temp -=2; // Clusterposition is ((position in FAT)-2). first two entries in FAT are reserved. |
cluster_temp *= (u32)SectorsPerCluster; // Calculate positon of first cluster. |
file->start_cluster = (FirstDataCluster + cluster_temp); |
file->directory_sector = (u32) file->cluster_pointer; |
file->cluster_pointer = file->start_cluster; // start reading the file with the first cluster. |
file->filesize = (u32) DirectoryEntry[rootentry].size; |
file->directory_index = (u8) rootentry; |
retvalue = 1; |
} |
rootentry++; |
returnvalue += fclose_(&FilePointer[cnt]); // try to close open file pointers |
} |
if(!retvalue) // file not found in this sector so take next sector. |
{ |
end_of_directory_not_reached = GetNextCluster(file); |
} |
|
} |
while((end_of_directory_not_reached) && (!retvalue)); |
return(retvalue); |
SDC_Deinit(); // uninitialize interface to sd-card |
Partition.IsValid = 0; // mark data in partition structure as invalid |
return(returnvalue); |
} |
|
|
/*****************************************************************************************************************************************************/ |
/* Function: void ScanSubDirectories(u8* fname, File_t *file); */ |
/* */ |
/* Description: This function scans the filename for subdirectories and changes the directory until the last directory is reached. */ |
/* here the specified file is searched. */ |
/* */ |
/* Returnvalue: */ |
/*****************************************************************************************************************************************************/ |
|
u8 ScanSubDirectories(u8 *fname, File_t *file) |
|
|
/*****************************************************************************************************************************************/ |
/* Function: GetNextCluster(File_t file); */ |
/* */ |
/* Description: This function finds the next datacluster of the file specified with File *File. */ |
/* */ |
/* Returnvalue: The function returns the next cluster or 0 if the last cluster has already reached. */ |
/*****************************************************************************************************************************************/ |
u16 GetNextCluster(File_t * File) |
{ |
u8 readpointer = 0; // pointer to read a character within the filepath. |
u8 writepointer = 0; // pointer to write a character into the string dirname. |
u8 dircnt = 0; // the number of subdirectories found in filepath. |
u8 dirname[11]; // temporary variable containing the name of a directory within the filepath. |
u8 retvalue = 1; // no error opening a subdirectory occured yet. |
u8 cnt = 0; // maximun number of characters in a path is 256; |
u16 cluster = 0; |
u32 fat_byte_offset, sector, byte; |
Fat16Entry_t * Fat; |
|
// analyze the fname sting |
while((fname[readpointer]!=0) && (cnt < 255)) // search the string until the end is reached. |
if(File == 0) return(cluster); |
// if sector is within the data area |
if(Partition.FirstDataSector <= File->FirstSectorOfCurrCluster) |
{ |
cnt++; |
if((fname[readpointer] == '/') && readpointer) // subdirectory found. ignore first "/" as directory. |
// determine current file cluster |
cluster = SectorToFat16Cluster(File->FirstSectorOfCurrCluster); |
// calculate byte offset in the fat for corresponding entry |
fat_byte_offset = ((u32)cluster)<<1; // two FAT bytes (16 bits) for every cluster |
// calculate the sector that contains the current cluster within the fat |
sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR); |
// calculate byte offset of the current cluster within that fat sector |
byte = fat_byte_offset % BYTES_PER_SECTOR; |
// read this sector to the file cache |
if(File->SectorInCache != sector) |
{ |
dircnt++; // count the number of subdirectories found within the filepath. |
File->SectorInCache = sector; // update sector stored in buffer |
SDC_GetSector(File->SectorInCache, File->Cache); // read sector from sd-card |
} |
// read the next cluster from cache |
Fat = (Fat16Entry_t *)(&(File->Cache[byte])); |
cluster = Fat->NextCluster; |
// if last cluster fat entry |
if(FAT16_CLUSTER_LAST_MIN <= cluster) |
{ |
cluster = 0; |
} |
readpointer++; |
else |
{ |
File->FirstSectorOfCurrCluster = Fat16ClusterToSector(cluster); |
File->SectorOfCurrCluster = 0; |
File->ByteOfCurrSector = 0; |
} |
} |
// fill dirname with spaces |
for(writepointer = 0; writepointer < 10; writepointer++) dirname[writepointer] = ' '; |
// if sector is within the root directory |
else if((Partition.FirstRootDirSector <= File->FirstSectorOfCurrCluster) && (File->FirstSectorOfCurrCluster < Partition.FirstDataSector)) |
{ |
if((File->FirstSectorOfCurrCluster + 1) == Partition.FirstDataSector) |
{ |
cluster = 0; |
} |
else |
{ |
File->FirstSectorOfCurrCluster++; |
File->SectorOfCurrCluster = 0; |
File->ByteOfCurrSector = 0; |
cluster = 1; |
} |
} |
return(cluster); |
} |
|
writepointer = 0; // start writing the dirname at the beginning. |
readpointer = 0; // start scanning the filename at the beginning. |
|
file->cluster_pointer = RootDirectory; // always start searching in the rootdirectory. |
file->attribute = _DIRECTORY; // the attribute of the item to be searched in the specified directory. |
/****************************************************************************************************************************************/ |
/* Function: FindNextFreeCluster(File_t *file); */ |
/* */ |
/* Description: This function looks in the fat to find the next free cluster */ |
/* */ |
/* Returnvalue: The function returns the cluster number of the next free cluster found within the fat. */ |
/****************************************************************************************************************************************/ |
u16 FindNextFreeCluster(File_t *File) |
{ |
u32 fat_sector; // current sector within the fat relative to the first sector of the fat. |
u32 curr_sector; // current sector |
u16 fat_entry; // index to an fatentry within the actual sector (256 fatentries are possible within one sector). |
u16 free_cluster = 0; // next free cluster number. |
Fat16Entry_t * Fat; |
|
while(dircnt && retvalue) // scan all subdirectories found before. |
if(File == 0) return(0); |
|
// start searching for an empty cluster at the beginning of the fat. |
fat_sector = 0; |
do |
{ |
if(fname[readpointer] != '/') // is the end of the subdirectory entry not reached yet? |
curr_sector = Partition.FirstFatSector + fat_sector; // calculate sector to read |
File->SectorInCache = curr_sector; // upate the sector number of file cache. |
SDC_GetSector(File->SectorInCache, File->Cache); // read sector of fat from sd-card. |
Fat = (Fat16Entry_t *)File->Cache; // set fat pointer to file cache |
|
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. |
{ |
// all characters must be upper case. |
// check if character is lower case (in between 0x61 and 0x7A) |
if((fname[readpointer]>0x60) && (fname[readpointer]<0x7B)) |
{ |
dirname[writepointer]=(fname[readpointer] - 0x20); // to upper case |
if(Fat[fat_entry].NextCluster == FAT16_CLUSTER_FREE) // empty cluster found!! |
{ |
Fat[fat_entry].NextCluster = FAT16_CLUSTER_LAST_MAX; // mark this fat-entry as used |
SDC_PutSector(File->SectorInCache, File->Cache); // and save the sector at the sd-card. |
|
free_cluster = (u16)(fat_sector * FAT16_ENTRIES_PER_SECTOR + (u32)fat_entry); |
fat_entry = FAT16_ENTRIES_PER_SECTOR; // terminate the search for a free cluster in this sector. |
} |
else |
{ |
dirname[writepointer]=fname[readpointer]; // was upper case |
} |
writepointer++; |
} |
else // '/' was found indicating new subdirectory |
{ |
dircnt--; |
if(!(SeekDirectoryEntry(dirname, file))) // was the seperated subdirectory not found? |
{ |
retvalue = 0; // leave the function with return(0) otherwise continue with the next subdirectory until all directories have been searched. |
} |
for(writepointer=0;writepointer<10;writepointer++) dirname[writepointer] = ' '; |
writepointer = 0; |
} |
readpointer++; // got next character |
} |
file->attribute = _FILE; // All subdirectories have been searched. the next thing to find is the specified file. |
return(retvalue); |
fat_sector++; // continue the search in next fat sector |
// repeat until the end of the fat is reached and no free cluster has been found so far |
}while((fat_sector < Partition.SectorsPerFat) && (!free_cluster)); |
return(free_cluster); |
} |
|
|
|
/********************************************************************************************************************************************/ |
/* Function: File_t * fopen_(u8* fname, s8 mode); */ |
/* */ |
/* Description: This function looks for the specified file in the rootdirectory of the drive. If the file is found the number of the */ |
/* corrosponding filepointer is returned. Only modes 'r' (reading) and 'a' append are implemented yet. */ |
/* */ |
/* Returnvalue: The filepointer to the file or 0 if faild. */ |
/********************************************************************************************************************************************/ |
File_t * fopen_(u8 *fname, s8 mode) |
/****************************************************************************************************************************************************/ |
/* Function: s16 fseek_(File *, s32 *, u8) */ |
/* */ |
/* Description: This function sets the pointer of the stream relative to the position */ |
/* specified by origin (SEEK_SET, SEEK_CUR, SEEK_END) */ |
/* Returnvalue: Is 1 if seek was successful */ |
/****************************************************************************************************************************************************/ |
s16 fseek_(File_t *File, s32 offset, s16 origin) |
{ |
u32 cluster_temp = 0; |
u8 name[11] = " "; |
u16 temp = 0; |
File_t *file = 0; |
s32 fposition = 0; |
s16 retvalue = 1; |
|
file = 0; |
// Look for an unused filepointer in the file pointer list? |
for(temp = 0; temp < __MAX_FILES_USED; temp++) |
switch(origin) |
{ |
if(FilePointer[temp].state == _UNUSED) // founbd an unused one |
{ |
file = &FilePointer[temp]; // set pointer to that entry |
FilePointer[temp].state = _USED; // mark it as used |
case SEEK_SET: // Fileposition relative to the beginning of the file. |
fposition = 0; |
break; |
} |
case SEEK_END: // Fileposition relative to the end of the file. |
fposition = (s32)File->Size; |
break; |
case SEEK_CUR: // Fileposition relative to the current position of the file. |
default: |
fposition = File->Position; |
break; |
} |
// if no unused file pointer was found return 0 |
if(file == 0) return(file); |
|
// initialize values |
file->start_cluster = 0; // Sectorpointer to the first sector of the first datacluster of the file. |
file->cluster_pointer = 0; // Pointer to the cluster which is edited at the moment. |
file->sector_index = 0; // The sector which is edited at the moment (cluster_pointer + sector_index). |
file->byte_index = 0; // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index). |
file->mode = mode; // mode of fileoperation (read,write) |
file->filesize = 0; // the size of the opened file in bytes. |
file->fileposition = 0; // pointer to a byte within the file 0 < fileposition < filesize |
file->sector_in_buffer = 0; // the last sector read, wich is still in the sectorbuffer. |
file->directory_sector = 0; // the sectorposition where the directoryentry has been made. |
file->directory_index = 0; // the index to the directoryentry within the specified sector. |
file->attribute = 0; // the attribute of the file opened. |
fposition += offset; |
|
if(ScanSubDirectories(&fname[0], file)) // Is the specified filepath available? |
if((fposition >= 0) && (fposition <= (s32)File->Size)) // is the pointer still within the file? |
{ |
SeperateFileName(&fname[0], &name[0]); // seperate the filename and attribute from the filepath and bring them in the correct format. |
file->attribute = _FILE; |
if(SeekDirectoryEntry(&name[0], file)) // if file was found |
// reset file position to start of the file |
File->FirstSectorOfCurrCluster = File->FirstSectorOfFirstCluster; |
File->SectorOfCurrCluster = 0; |
File->ByteOfCurrSector = 0; |
File->Position = 0; |
|
while(File->Position < fposition) // repeat until the current position is less than target |
{ |
if(mode == 'a') // open existing file for writing (append data at the end of the file) |
{ |
fseek_(file, 0, SEEK_END); // fseek points to the end of the file |
} |
return(file); |
} |
else |
{ |
if((mode == 'a') || (mode == 'w')) // specified file doesn't exist so create new file for writing data. |
{ |
cluster_temp = (u32)FindNextFreeCluster(file); // the next free cluster on the disk. |
if(cluster_temp) // if a free cluster is available: |
File->Position++; // increment file position |
File->ByteOfCurrSector++; // next byte in current sector |
if(File->ByteOfCurrSector >= BYTES_PER_SECTOR) |
{ |
File->ByteOfCurrSector = 0; // reading at the beginning of new sector. |
File->SectorOfCurrCluster++; // continue reading in next sector |
if(File->SectorOfCurrCluster >= Partition.SectorsPerCluster) // if end of cluster is reached, the next datacluster has to be searched in the FAT. |
{ |
temp = (u16)cluster_temp; // remember the index of the free datacluster found for the directory entry. |
cluster_temp -=2; // Clusterposition is ((position in FAT)-2). first two entries in FAT are reserved. |
cluster_temp *= SectorsPerCluster; // Calculate relative sectorindex of first datacluster. |
file->start_cluster = (FirstDataCluster + cluster_temp); // Calculate absolute sectorposition of first datacluster. |
file->cluster_pointer = file->start_cluster; // start reading the file with the first sector of the first datacluster. |
if(CreateDirectoryEntry(&name[0],temp,file,_FILE)) // Could an entry for the new file in the rootdirectory be created? |
if(GetNextCluster(File)) // Sets the clusterpointer of the file to the next datacluster. |
{ |
return(file); |
} |
} |
} |
} |
File->SectorOfCurrCluster = 0; |
} |
else // the last cluster was allready reached |
{ |
File->SectorOfCurrCluster--; // jump back to the ast sector in the last cluster |
File->ByteOfCurrSector = BYTES_PER_SECTOR; // set ByteOfCurrSector one byte over sector end |
} |
} |
} |
} |
} |
return(0); |
if(File->Position == fposition) retvalue = 0; |
return(retvalue); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fflush_(File *file); |
// |
// Description: This function writes the data already in the buffer but not yet written to the file. |
// |
//________________________________________________________________________________________________________________________________________ |
|
s16 fflush_(File_t *file) |
/****************************************************************************************************************************************/ |
/* Function: u16 AppendCluster(File *file); */ |
/* */ |
/* Description: This function looks in the fat to find the next free cluster and appends it to the file. */ |
/* */ |
/* Returnvalue: The function returns the appened cluster number or 0 of no cluster was appended. */ |
/****************************************************************************************************************************************/ |
u16 AppendCluster(File_t *File) |
{ |
u16 time=0; |
u16 date=0; |
|
#ifdef __USE_TIME_DATE_ATTRIBUTE // has the date and time attribute of the file to be set? |
u16 last_cluster, new_cluster = 0; |
u32 fat_byte_offset, sector, byte; |
Fat16Entry_t * Fat; |
|
time = (((rtctime.hour)<<11) | ((rtctime.minute)<<5) | rtctime.second); |
date = ((((rtctime.year)-1980) <<9) | ((rtctime.month) <<5) | rtctime.day); |
new_cluster = FindNextFreeCluster(File); // the next free cluster found on the disk. |
if(new_cluster) |
{ // A free cluster was found and can be added to the end of the file. |
fseek_(File, 0, SEEK_END); // jump to the end of the file |
last_cluster = SectorToFat16Cluster(File->FirstSectorOfCurrCluster); // determine current file cluster |
fat_byte_offset = ((u32)last_cluster)<<1; |
sector = Partition.FirstFatSector + ( fat_byte_offset / BYTES_PER_SECTOR); |
byte = fat_byte_offset % BYTES_PER_SECTOR; |
|
#endif |
|
|
if(file && file->mode =='a') |
{ |
if(file->byte_index > 0) // has data been added to the file? |
if(File->SectorInCache != sector) |
{ |
SDC_PutSector((u32)(file->cluster_pointer + file->sector_index),file->buffer); // save the data still in the buffer |
} |
SDC_GetSector((u32)file->directory_sector,file->buffer); // read the directoryentry for this file. |
DirectoryEntry = (DirEntry_t *)file->buffer; |
DirectoryEntry[file->directory_index].size = (u32) file->filesize; |
DirectoryEntry[file->directory_index].time = (u16) time; |
DirectoryEntry[file->directory_index].date = (u16) date; |
SDC_PutSector((u32)file->directory_sector,file->buffer); |
File->SectorInCache = sector; // update sector stored in buffer |
if(SD_SUCCESS != SDC_GetSector(File->SectorInCache, File->Cache)) // read sector from sd-card |
{ |
return(0); |
} |
} |
Fat = (Fat16Entry_t *)(&(File->Cache[byte])); |
Fat->NextCluster = new_cluster; // append the free cluster to the end of the file in the FAT. |
if(SD_SUCCESS != SDC_PutSector(File->SectorInCache, File->Cache)) // save the modified sector to the FAT. |
{ |
return(0); |
} |
File->FirstSectorOfCurrCluster = Fat16ClusterToSector(new_cluster); |
File->SectorOfCurrCluster = 0; |
File->ByteOfCurrSector = 0; |
} |
return(0); |
return(new_cluster); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fclose_(File *file); |
// |
// Description: This function closes the open file by writing the remaining data from the buffer to the device and entering the filesize |
// in the directory entry. |
//________________________________________________________________________________________________________________________________________ |
/****************************************************************************************************************************************************/ |
/* Function: DirectoryEntryExist(u8 *, File_t *) */ |
/* */ |
/* Description: This function searches all possible dir entries until the file or directory is found or the end of thedirectory is reached */ |
/* */ |
/* Returnvalue: This function returns 1 if the directory entry specified was found. */ |
/****************************************************************************************************************************************************/ |
u8 DirectoryEntryExist(u8 *dirname, File_t *File) |
{ |
u32 dir_sector, max_dir_sector, curr_sector; |
u16 dir_entry = 0; |
|
void fclose_(File_t *file) |
{ |
u8 cnt = 0; |
|
for(cnt=0;cnt<__MAX_FILES_USED;cnt++) |
u16 end_of_directory_not_reached = 0; |
u8 i = 0; |
u8 retvalue = 0; |
DirEntry_t * Dir; |
|
if(File == 0) return(0); |
// dir entries can be searched only in filesclusters that have |
// the dir-flag set in its attribute or within the root directory |
|
// within the root directory area its allways valid to search a directory entry |
if((Partition.FirstRootDirSector <= File->DirectorySector) && (File->DirectorySector < Partition.FirstDataSector)) |
{ |
if(&FilePointer[cnt] == file) // filepointer to be freed found? |
{ |
FilePointer[cnt].state = _UNUSED; |
max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR; |
} |
// check if directory entry of current file has the dir-flag set |
else if(Partition.FirstDataSector <= File->DirectorySector) |
{ |
max_dir_sector = Partition.SectorsPerCluster; |
File->SectorInCache = File->DirectorySector; // upate the sector number of file cache. |
SDC_GetSector(File->SectorInCache, File->Cache); // read in the sector. |
Dir = (DirEntry_t *)File->Cache; // set pointer to directory |
if(Dir[File->DirectoryIndex].Attribute != ATTR_SUBDIRECTORY) |
{ // current file is not a directory |
return (0); |
} |
} |
else return (0); // bad sector range for directory sector of the file |
|
fflush_(file); // save buffercontent to the sdcard |
do // loop over all clusters of the curernt directory |
{ |
dir_sector = 0; // reset sector counter within a new cluster |
do // loop over all sectors of a cluster or all sectors of the root directory |
{ |
curr_sector = File->FirstSectorOfCurrCluster + dir_sector; // calculate sector number |
File->SectorInCache = curr_sector; // upate the sector number of file cache. |
SDC_GetSector(File->SectorInCache, File->Cache); // read in the sector. |
Dir = (DirEntry_t *)File->Cache; // set pointer to directory |
// search all directory entries of a sector |
for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++) |
{ |
switch(Dir[dir_entry].Name[0]) |
{ |
case SLOT_EMPTY: |
case SLOT_DELETED: |
// ignore empty or deleted dir entries |
break; |
default: |
// check attributes before names are compared will safe performance |
if (Dir[dir_entry].Attribute != File->Attribute) break; // attribute must match |
// compare the dirname to filename (first 9 characters including 8 char of the dirname and padded space char.) |
i = 0; |
while((i < 11) && (Dir[dir_entry].Name[i] == dirname[i])) i++; |
if (i < 10) break; // names does not match |
File->Attribute = Dir[dir_entry].Attribute; // store attribute of dir entry |
File->FirstSectorOfFirstCluster = Fat16ClusterToSector(Dir[dir_entry].StartCluster); // set start cluster sector |
File->FirstSectorOfCurrCluster = File->FirstSectorOfFirstCluster; |
File->DirectorySector = File->SectorInCache; // store position of dir entry of that file |
File->DirectoryIndex = dir_entry; |
File->Size = Dir[dir_entry].Size; |
retvalue = 1; // mark as found |
dir_entry = DIRENTRIES_PER_SECTOR; // stop for-loop |
} // end of first byte of name check |
} |
dir_sector++; // search next sector |
// stop if we reached the end of the cluster or the end of the root dir |
}while((dir_sector < max_dir_sector) && (!retvalue)); |
|
file->start_cluster = 0; // Sectorpointer to the first sector of the first datacluster of the file. |
file->cluster_pointer = 0; // Pointer to the cluster which is edited at the moment. |
file->sector_index = 0; // The sector which is edited at the moment (cluster_pointer + sector_index). |
file->byte_index = 0; // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index). |
file->mode = 0; // mode of fileoperation (read,write) |
file->filesize = 0; // the size of the opend file in bytes. |
file->fileposition = 0; // pointer to a character within the file 0 < fileposition < filesize |
file->sector_in_buffer = 0; // the last sector read, wich is still in the sectorbuffer. |
file->directory_sector = 0; // the sectorposition where the directoryentry has been made. |
file->directory_index = 0; // the index to the directoryentry within the specified sector. |
file->attribute = 0; // the attribute of the file opened. |
} |
// if we are seaching in the data area and the file not found in this cluster so take next cluster. |
if(!retvalue && ( Partition.FirstDataSector <= File->FirstSectorOfCurrCluster)) |
{ |
end_of_directory_not_reached = GetNextCluster(File); // updates File->FirstSectorOfCurrCluster |
} |
}while((end_of_directory_not_reached) && (!retvalue)); |
return(retvalue); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: s32 fread_(void *buffer, s32 size, s32 count, File *file); |
// |
// Description: This function reads count objects of the specified size from the actual position of the file to the specified buffer. |
// |
// Returnvalue: The function returns the number of objects (not bytes) read from the file. |
// |
//________________________________________________________________________________________________________________________________________ |
|
u32 fread_(void *buffer, u32 size, u32 count, File_t *file) |
/****************************************************************************************************************************************/ |
/* Function: CreateDirectoryEntry(u8 *, u16, File_t *) */ |
/* */ |
/* Description: This function looks for the next free position in the directory and creates an entry. */ |
/* The type of an directory entry is specified by the file attribute. */ |
/* */ |
/* Returnvalue: Return 0 on error */ |
/****************************************************************************************************************************************/ |
u8 CreateDirectoryEntry(u8 *name, File_t *File) |
{ |
u32 object_cnt = 0; // count the number of objects read from the file. |
u32 object_size = 0; // count the number of bytes read from the actual object. |
u8 *buff_pnt = 0; // a pointer to the actual bufferposition. |
u8 success = 1; // no error occured during read operation to the file. |
u32 dir_sector, max_dir_sector, curr_sector; |
u16 dir_entry = 0; |
u16 cluster = 0; |
u16 end_of_directory_not_reached = 0; |
u8 i = 0; |
u8 retvalue = 0; |
DirEntry_t *Dir; |
|
|
if(File == 0) return (0); |
// It is not checked here that the dir entry that should be created is already existent! |
|
buff_pnt = (u8 *) buffer; // cast the void pointer to an u8 * |
|
while((object_cnt < count) && success) |
// Dir entries can be created only in file-clusters that have |
// the dir-flag set in its attribute or within the root directory |
|
// within the root directory area its allways valid to create a directory entry |
if((Partition.FirstRootDirSector <= File->DirectorySector) && (File->DirectorySector < Partition.FirstDataSector)) |
{ |
object_size = size; |
while((size > 0) && success) |
max_dir_sector = (Partition.MaxRootEntries * DIRENTRY_SIZE)/BYTES_PER_SECTOR; |
} |
// check if the directory entry of current file has the dir-flag set |
else if(Partition.FirstDataSector <= File->DirectorySector) |
{ |
max_dir_sector = Partition.SectorsPerCluster; |
File->SectorInCache = File->DirectorySector; // update the sector number of file cache. |
SDC_GetSector(File->SectorInCache, File->Cache); // read in the sector. |
Dir = (DirEntry_t *)File->Cache; // set pointer to directory |
if(Dir[File->DirectoryIndex].Attribute != ATTR_SUBDIRECTORY) |
{ // current file is not a directory |
return (0); |
} |
} |
else return (0); // bad sector range for directory sector of the file |
|
do // loop over all clusters of current directory |
{ |
dir_sector = 0; // reset sector counter within a new cluster |
do // loop over all sectors of a cluster or all sectors of the root directory |
{ |
*buff_pnt = (u8) fgetchar_(file); // read a byte from the buffer to the opened file. |
buff_pnt++; |
size--; |
curr_sector = File->FirstSectorOfCurrCluster + dir_sector; // calculate sector number |
File->SectorInCache = curr_sector; // upate the sector number of file cache. |
SDC_GetSector(File->SectorInCache, File->Cache); // read in the sector. |
Dir = (DirEntry_t *)File->Cache; // set pointer to directory |
// search all directory entries of a sector |
for(dir_entry = 0; dir_entry < DIRENTRIES_PER_SECTOR; dir_entry++) |
{ // check if current direntry is available |
if((Dir[dir_entry].Name[0] == SLOT_EMPTY) || (Dir[dir_entry].Name[0] == SLOT_DELETED)) |
{ // a free direntry was found |
cluster = FindNextFreeCluster(File); // get the next free cluster on the disk. |
if(cluster) |
{ |
for(i = 0; i < 11; i++) Dir[dir_entry].Name[i] = name[i]; // Set dir name |
Dir[dir_entry].Attribute = File->Attribute; // Set the fileattribute to archive to reserve the directoryentry. |
Dir[dir_entry].StartCluster = cluster; // copy the location of the first datacluster to the directoryentry. |
Dir[dir_entry].Size = 0; // the new createted file has no content yet. |
SDC_PutSector(File->SectorInCache, File->Cache); // and save the sector containing new directory entry back to the sd-card. |
File->FirstSectorOfFirstCluster = Fat16ClusterToSector(cluster); // Calculate absolute sectorposition of first datacluster. |
File->FirstSectorOfCurrCluster = File->FirstSectorOfFirstCluster; // Start reading the file with the first sector of the first datacluster. |
File->SectorOfCurrCluster = 0; // reset sector of cureen cluster |
File->ByteOfCurrSector = 0; // reset byte location within the current sector |
File->Size = 0; // new file has no size |
File->DirectorySector = curr_sector; |
File->DirectoryIndex = dir_entry; |
retvalue = 1; |
dir_entry = DIRENTRIES_PER_SECTOR; // stop for-loop |
} |
else |
{ //no free cluster found in the fat |
return (0); |
} |
} |
} |
dir_sector++; // search next sector |
// stop if we reached the end of the cluster or the end of the root dir |
}while((dir_sector < max_dir_sector) && (!retvalue)); |
|
// if we are seaching in the data area and the file not found in this cluster so take next cluster. |
if(!retvalue && ( Partition.FirstDataSector <= File->FirstSectorOfCurrCluster)) |
{ |
end_of_directory_not_reached = GetNextCluster(File); // updates File->FirstSectorOfCurrCluster |
} |
if(success) object_cnt++; |
} |
|
return(object_cnt); // return the number of objects succesfully read from the file |
}while((end_of_directory_not_reached) && (!retvalue)); |
// Perhaps we are at the end of the last cluster of a directory file an have no free direntry found. |
// Then we would need to add a cluster to that file and create the new direntry there. |
// This code is not implemented yet, because its occurs only if more that 32*32=1024 direntries are |
// within a subdirectory of root. |
return(retvalue); // return 1 if file has been created otherwise return 0. |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: s32 fwrite_(void *buffer, s32 size, s32 count, File *file); |
// |
// Description: This function writes count objects of the specified size from the buffer to the actual positon within the file. |
// |
// Returnvalue: The function returns the number of objects (not bytes) written to the file. |
// |
//________________________________________________________________________________________________________________________________________ |
|
u32 fwrite_(void *buffer, u32 size, u32 count, File_t *file) |
/********************************************************************************************************************************************/ |
/* Function: File_t * fopen_(u8* filename, s8 mode); */ |
/* */ |
/* Description: This function looks for the specified file in the rootdirectory of the drive. If the file is found the number of the */ |
/* corrosponding filepointer is returned. Only modes 'r' (reading) and 'a' append are implemented yet. */ |
/* */ |
/* Returnvalue: The filepointer to the file or 0 if faild. */ |
/********************************************************************************************************************************************/ |
File_t * fopen_(const u8 *filename, const s8 mode) |
{ |
u32 object_cnt = 0; // count the number of objects written to the file. |
u32 object_size = 0; // count the number of bytes written from the actual object. |
u8 *buff_pnt = 0; // a pointer to the actual bufferposition. |
u8 success = 1; // no error occured during write operation to the file. |
u8 name[11]; |
u8 *filepath = 0; |
File_t *File = 0; |
u8 i; |
|
buff_pnt = (u8 *) buffer; // cast the void pointer to an u8 * |
|
while((object_cnt < count) && success) |
// Look for an unused filepointer in the file pointer list? |
for(i = 0; i < FILE_MAX_OPEN; i++) |
{ |
object_size = size; |
while((size > 0) && success) |
if(FilePointer[i].State == FSTATE_UNUSED) // found an unused one |
{ |
success = fputchar_(file, *buff_pnt); // write a byte from the buffer to the opened file. |
buff_pnt++; |
size--; |
File = &FilePointer[i]; // set pointer to that entry |
FilePointer[i].State = FSTATE_USED; // mark it as used |
break; |
} |
if(success) object_cnt++; |
} |
|
return(object_cnt); // return the number of objects succesfully written to the file |
} // (!!!!! objects and not bytes !!!!) |
} |
// if no unused file pointer was found return 0 |
if(File == 0) return(File); |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: s16 fseek_(File *, s32, s16) |
// |
// Description: This function sets the pointer of the stream relative to the position |
// specified by origin (SEEK_SET, SEEK_CUR, SEEK_END). |
// |
//________________________________________________________________________________________________________________________________________ |
// initialize values |
File->FirstSectorOfFirstCluster = 0; // Sectorpointer to the first sector of the first datacluster of the file. |
File->FirstSectorOfCurrCluster = 0; // Pointer to the cluster which is edited at the moment. |
File->SectorOfCurrCluster = 0; // The sector which is edited at the moment (cluster_pointer + sector_index). |
File->ByteOfCurrSector = 0; // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index). |
File->Mode = mode; // mode of fileoperation (read,write) |
File->Size = 0; // the size of the opened file in bytes. |
File->Position = 0; // pointer to a byte within the file 0 < fileposition < filesize |
File->SectorInCache = 0; // the last sector read, wich is still in the sectorbuffer. |
File->DirectorySector = 0; // the sectorposition where the directoryentry has been made. |
File->DirectoryIndex = 0; // the index to the directoryentry within the specified sector. |
File->Attribute = 0; // the attribute of the file opened. |
|
s16 fseek_(File_t *file, s32 offset, s16 origin) |
{ |
s32 fposition = 0; |
s16 retvalue = 1; |
u32 temp = 0; |
|
//...................................................... |
if(origin == SEEK_SET) // Fileposition relative to the beginning of the file. |
// trace along the filepath by checking if the directories |
filepath = (u8*)filename; // start a the beginning of the filename string |
File->DirectorySector = Partition.FirstRootDirSector; // Root of RootDirectory is Root |
File->FirstSectorOfCurrCluster = Partition.FirstRootDirSector; // start search in RootDirectory |
File->Attribute = ATTR_SUBDIRECTORY; //check for directory |
while(*filepath != 0) |
{ |
fposition = 0; |
} |
//...................................................... |
else if(origin == SEEK_END) // Fileposition relative to the end of the file. |
{ |
fposition = (s32) file->filesize; |
} |
//...................................................... |
else if(origin == SEEK_CUR) // Fileposition relative to the current position of the file. |
{ |
fposition = file->fileposition; |
} |
|
fposition += offset; |
|
if((fposition >= 0) && (fposition <= (s32)file->filesize)) // is the pointer still within the file? |
{ |
retvalue = 0; |
file->sector_index = 0; |
file->byte_index = 0; |
file->fileposition = 0; |
file->cluster_pointer = file->start_cluster; |
|
while(file->fileposition < fposition) |
if(SeperateDirName(filepath, name, filepath)) // separate dirname from filepath string |
{ |
file->fileposition++; |
if(file->byte_index < 511) |
if(!DirectoryEntryExist(name, File)) |
{ |
file->byte_index++; |
goto errorout; // subdirectory does not exist |
} |
else |
{ |
file->byte_index=0; // reading at the beginning of new sector. |
file->sector_index++; // continue reading in next sector |
if(file->sector_index >= SectorsPerCluster) // When end of cluster is reached, the next datacluster has to be searched in the FAT. |
{ |
if(file->fileposition < fposition) |
{ |
file->sector_index = 0; // start reading new cluster at first sector of the cluster. |
GetNextCluster(file); // Sets the clusterpointer of the file to the next datacluster. |
} |
} |
} |
} |
if(file->byte_index) |
else // error seperating the subpath |
{ |
temp = (u32)((u32)file->cluster_pointer + (u32)file->sector_index); |
SDC_GetSector((u32)temp,file->buffer); // FileBuffer will be written at once at the end of the cluster and has to be updated. |
goto errorout; // bad subdir format |
} |
} |
return(retvalue); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fgetchar_(File *file); |
// |
// Description: This function reads and returns one character from the specified file. Is the end of the actual sector reached the |
// next sector of the cluster is read. Is the last sector of the cluster read the next cluster will be searched in FAT. |
// Returnvalue: The function returns the character read from the specified memorylocation as u8 casted to s16 or EOF. |
//________________________________________________________________________________________________________________________________________ |
|
s16 fgetchar_(File_t *file) |
{ |
s16 c = EOF; |
u32 temp1; |
|
if(file->filesize > 0) // wen the end of the file is not reached, get the next character. |
} |
// now name cointains the name of the file at the end of the filepath |
File->Attribute = ATTR_ARCHIVE; |
if(DirectoryEntryExist(name, File)) // file exist |
{ |
temp1 = (u32)file->cluster_pointer; // calculate the adress of the next character to be read. |
temp1 += (u32)file->sector_index; |
|
if(file->sector_in_buffer != temp1) // Has the content of the buffer been modified and has to be updated? |
if(mode == 'a') // if mode is: append to file |
{ |
SDC_GetSector((u32)temp1,file->buffer); // Read the calculated cluster. |
file->sector_in_buffer = (u32)temp1; |
} |
c = (s16) file->buffer[file->byte_index]; |
file->filesize--; // decrement the number of characters available. |
|
if(file->byte_index < 511) // continue reading from this sector until the end of the sector is reached. |
{ |
file->byte_index++; |
fseek_(File, 0, SEEK_END); // point to the end of the file |
} |
else // has the end of an sector been reached-> |
// else w /r ?? |
return(File); |
} |
else // file does not exist |
{ |
if((mode == 'a') || (mode == 'w')) |
{ |
file->byte_index=0; // continue reading at the beginning - |
file->sector_index++; // of new sector. |
if(file->sector_index >= SectorsPerCluster) // When the end of an cluster is reached, the next datacluster has to be searched in the FAT. |
if(CreateDirectoryEntry(name, File)) // Could an entry for the new file in the directory be created? |
{ |
file->sector_index = 0; // start reading new cluster at first sector of the cluster. |
GetNextCluster(file); // Sets the clusterpointer of the file to the next datacluster. |
} |
return(File); |
} |
// else directory entry could be created at the current location --> error |
} |
// else opend for 'r' and file is not existent --> error |
} |
return(c); |
|
errorout: |
File->State = FSTATE_UNUSED; // release file pointer |
File = 0; |
return(File); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fputchar_(File *file); |
// |
// Description: This function writes a byte to the specified file and takes care of writing the necessary FAT- Entries. |
// |
// Returnvalue: The function returns a value of 0 if the data could not be written. |
//________________________________________________________________________________________________________________________________________ |
/****************************************************************************************************************************************************/ |
/* Function: fflush_(File *); */ |
/* */ |
/* Description: This function writes the data already in the buffer but not yet written to the file. */ |
/* */ |
/* Returnvalue: 0 on success EOF on error */ |
/****************************************************************************************************************************************************/ |
s16 fflush_(File_t *File) |
{ |
u16 time = 0; |
u16 date = 0; |
DirEntry_t *Dir; |
|
u8 fputchar_(File_t *file, s8 c) |
{ |
u32 ul_temp = 0; |
u8 retvalue = 1; |
#ifdef __USE_TIME_DATE_ATTRIBUTE // has the date and time attribute of the file to be set? |
time = (((rtctime.hour)<<11) | ((rtctime.minute)<<5) | rtctime.second); |
date = ((((rtctime.year)-1980) <<9) | ((rtctime.month) <<5) | rtctime.day); |
#endif |
|
if(file->sector_index >= SectorsPerCluster) // if end of the cluster is reached, find next free cluster |
if(File == 0) return (EOF); |
|
if(File->Mode == 'a') |
{ |
file->sector_index = 0; |
if(!AppendCluster(file)) retvalue = 0; // append a new and free cluster at the end of the file. |
} |
|
file->buffer[file->byte_index] = c; // write databyte into the buffer. The byte will be written to the device at once |
if(file->filesize == file->fileposition) file->filesize++; // a character has been written to the file so the size is inkremented but only when the character has been added at the end of the file. |
file->fileposition++; // the actual positon within the file. |
// if the buffer contains the complete sectordata. |
if(file->byte_index < 511) // if the end of this sector is not reached yet |
{ |
file->byte_index++; // the next byte will be written to the next byteposition in this sector. |
} |
else // otherwise the data in the sectorbuffer will be written to the device and the next sector will be selected. |
{ |
ul_temp = (u32)file->cluster_pointer; |
ul_temp += (u32)file->sector_index; |
if(File->ByteOfCurrSector > 0) // has data been added to the file? |
{ |
if(SD_SUCCESS != SDC_PutSector(File->SectorInCache, File->Cache))// save the data still in the buffer |
{ |
return(EOF); |
} |
} |
File->SectorInCache = File->DirectorySector; |
if(SD_SUCCESS != SDC_GetSector(File->SectorInCache, File->Cache)) // read the directory entry for this file. |
{ |
return(EOF); |
} |
|
SDC_PutSector((u32)ul_temp,file->buffer); |
file->byte_index=0; // and the next byte will be written at the beginning of this new sector. |
file->sector_index++; |
if(file->sector_index >= SectorsPerCluster) // if end of the cluster is reached, find next free cluster |
Dir = (DirEntry_t *)File->Cache; |
Dir[File->DirectoryIndex].Size = File->Size; // update file size |
Dir[File->DirectoryIndex].Time = time; // update time |
Dir[File->DirectoryIndex].Date = date; // update date |
if(SD_SUCCESS != SDC_PutSector(File->SectorInCache, File->Cache)) // write back to sd-card |
{ |
file->sector_index = 0; |
if(!AppendCluster(file)) retvalue = 0; // append a new and free cluster at the end of the file. |
return(EOF); |
} |
} |
return(retvalue); |
return(0); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fputs_(File *file); |
// |
// Description: This function writes a string to the specified file. |
// |
//________________________________________________________________________________________________________________________________________ |
/****************************************************************************************************************************************/ |
/* Function: fclose_(File *file); */ |
/* */ |
/* Description: This function closes the open file by writing the remaining data */ |
/* from the buffer to the device and entering the filesize in the directory entry. */ |
/* */ |
/* Returnvalue: 0 on success EOF on error */ |
/****************************************************************************************************************************************/ |
s16 fclose_(File_t *File) |
{ |
u8 cnt = 0; |
s16 returnvalue = EOF; |
|
u8 fputs_(File_t *file,s8 * string) |
{ |
u8 i=0; |
|
while(string[i] != 0) |
if(File == 0) return(returnvalue); |
for(cnt = 0; cnt < FILE_MAX_OPEN; cnt++) |
{ |
fputchar_(file,string[i]); |
i++; |
if(&FilePointer[cnt] == File) // filepointer to be freed found? |
{ |
returnvalue = fflush_(File); // save cache content to the sdcard |
File->State = FSTATE_UNUSED; |
File->FirstSectorOfFirstCluster = 0; // Sectorpointer to the first sector of the first datacluster of the file. |
File->FirstSectorOfCurrCluster = 0; |
File->SectorOfCurrCluster = 0; // Pointer to the cluster which is edited at the moment. |
File->SectorOfCurrCluster = 0; // The sector which is edited at the moment (cluster_pointer + sector_index). |
File->ByteOfCurrSector = 0; // The bytelocation within the current sector (cluster_pointer + sector_index + byte_index). |
File->Mode = 0; // mode of fileoperation (read,write) |
File->Size = 0; // the size of the opend file in bytes. |
File->Position = 0; // pointer to a character within the file 0 < fileposition < filesize |
File->SectorInCache = 0; // the last sector read, wich is still in the sectorbuffer. |
File->DirectorySector = 0; // the sectorposition where the directoryentry has been made. |
File->DirectoryIndex = 0; // the index to the directoryentry within the specified sector. |
File->Attribute = 0; // the attribute of the file opened. |
} |
} |
return(0); |
return(returnvalue); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: fgets_(File *file); |
// |
// Description: This function reads a string from the file to the specifies string. |
// |
// Returnvalue: A pointer to the string written from the file. |
//________________________________________________________________________________________________________________________________________ |
|
s8 * fgets_(s8 *string, s16 count, File_t *file) |
{ |
s16 buff_pnt = 0; |
s16 buff_tmp = 0; |
u8 state = 0; // Variable used for a statemachine to recognize the end of a line. |
/********************************************************************************************************************************************/ |
/* Function: fgetc_(File *file); */ |
/* */ |
/* Description: This function reads and returns one character from the specified file. Is the end of the actual sector reached the */ |
/* next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT. */ |
/* */ |
/* Returnvalue: The function returns the character read from the specified memorylocation as u8 casted to s16 or EOF. */ |
/********************************************************************************************************************************************/ |
s16 fgetc_(File_t *File) |
{ |
s16 c = EOF; |
u32 curr_sector; |
|
while(count > 1) // read the count-1 characters from the file to the string. |
if(File == 0) return(c); |
// if the end of the file is not reached, get the next character. |
if((0 < File->Size) && (File->Position < File->Size) ) |
{ |
buff_tmp = fgetchar_(file); // read a character from the opened file. |
switch(state) |
curr_sector = File->FirstSectorOfCurrCluster; // calculate the sector of the next character to be read. |
curr_sector += File->SectorOfCurrCluster; |
|
if(File->SectorInCache != curr_sector) |
{ |
case 0: |
if(buff_tmp == 0x0A)// state++; |
File->SectorInCache = curr_sector; |
SDC_GetSector(File->SectorInCache, File->Cache); |
} |
c = (s16) File->Cache[File->ByteOfCurrSector]; |
File->Position++; // increment file position |
File->ByteOfCurrSector++; // goto next byte in sector |
if(File->ByteOfCurrSector >= BYTES_PER_SECTOR) // if end of sector |
{ |
File->ByteOfCurrSector = 0; // reset byte location |
File->SectorOfCurrCluster++; // next sector |
if(File->SectorOfCurrCluster >= Partition.SectorsPerCluster) // if end of cluster is reached, the next datacluster has to be searched in the FAT. |
{ |
|
if(GetNextCluster(File)) // Sets the clusterpointer of the file to the next datacluster. |
{ |
count = 1; |
File->SectorOfCurrCluster = 0; // start reading new cluster at first sector of the cluster. |
} |
state = 0; |
break; |
|
case 1: |
if(buff_tmp == 0x0A) |
else // the last cluster was allready reached |
{ |
count = 1; |
File->SectorOfCurrCluster--; // jump back to the last sector in the last cluster |
File->ByteOfCurrSector = BYTES_PER_SECTOR; // set ByteOfCurrSector one byte over sector end |
} |
state = 0; |
break; |
} |
} |
if(buff_tmp == EOF) {buff_tmp = 0; count = 1;} // is the end of the file reached, terminate the string with zero. |
string[buff_pnt] = (s8) buff_tmp; |
count--; |
buff_pnt++; |
} |
string[buff_pnt] = 0; |
return(string); |
return(c); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u8 fexist_(u8*, File *file); |
// |
// Description: This function searches the specified file and returns 0 if the file was not found. |
// |
// |
// Return: 0 = file does not exist |
// 1 = file exists |
//________________________________________________________________________________________________________________________________________ |
|
u8 fexist_(u8 *fname) |
{ |
File_t *file; |
/********************************************************************************************************************************************/ |
/* Function: fputc_( const s8 c, File *File); */ |
/* */ |
/* Description: This function writes a byte to the specified file and takes care of writing the necessary FAT- Entries. */ |
/* next sector of the cluster is read. If the last sector of the cluster read the next cluster will be searched in FAT. */ |
/* */ |
/* Returnvalue: The function returns the character written to the stream or EOF on error. */ |
/********************************************************************************************************************************************/ |
s16 fputc_(const u8 c, File_t *File) |
{ |
u32 curr_sector = 0; |
|
if((file = fopen_(fname,'r')) != 0) |
// If file position equals to file size, then the end of file has reached. |
// In this chase it has to be checked that the ByteOfCurrSector is BYTES_PER_SECTOR |
// and a new cluster should be appended. |
if((File->Position = File->Size) && (File->ByteOfCurrSector >= BYTES_PER_SECTOR)) |
{ |
fclose_(file); |
return(1); |
if(!AppendCluster(File)) return(EOF); |
} |
else |
|
curr_sector = File->FirstSectorOfCurrCluster; |
curr_sector += File->SectorOfCurrCluster; |
if(File->SectorInCache != curr_sector) |
{ |
return(0); |
File->SectorInCache = curr_sector; |
if(SD_SUCCESS != SDC_GetSector(File->SectorInCache, File->Cache)) |
{ |
return(EOF); |
} |
} |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: GetNextCluster(File *file); |
// |
// Description: This function finds the next datacluster of the file specified with File *file. |
// |
// Returnvalue: The function returns "0" if the last cluster has already been reached. |
//________________________________________________________________________________________________________________________________________ |
|
u16 GetNextCluster(File_t *file) |
{ |
u32 fat_pointer = 0; |
u32 fat_sector_offset = 0; |
u32 ul_tmp = 0; |
u8 retvalue = 0; // no new cluster found yet. |
|
|
if((file->cluster_pointer >= RootDirectory) && (file->cluster_pointer < (RootDirectory + 31))) |
{ // Is the next cluster searched within the rootdirectory and available? |
file->cluster_pointer++; // the rootdirectory is a linear adress space of 32 clusters. |
retvalue = 1; // and the next cluster has been found. |
} |
else if(file->cluster_pointer > (RootDirectory + 31)) // The specified cluster is within the FAT. |
{ |
fat_sector_offset = ((file->cluster_pointer) - (FirstDataCluster)); // Calculate index of actual cluster within the FAT. |
fat_sector_offset /= SectorsPerCluster; // calculate the index of the actual sector within the FAT. |
fat_sector_offset += 2; // In Fat16 clusterpositions have an offset of two. |
fat_pointer = (fat_sector_offset%0x100); // Calculate the sector within the cluster. |
fat_sector_offset = (fat_sector_offset>>8); // and the position within the sector. |
|
SDC_GetSector((u32)(FileAllocationTable + fat_sector_offset),file->buffer); |
file->sector_in_buffer = (FileAllocationTable + fat_sector_offset); // Mark that new sector has been read. |
|
ul_tmp = (u32)file->buffer[((fat_pointer << 1)+1)]; // Read next sector information from calculated clusterposition. |
ul_tmp = (ul_tmp << 8); |
ul_tmp |= (u32)file->buffer[(fat_pointer << 1)]; |
ul_tmp -=2; // next datacluster is clusterposition in fat - 2. |
ul_tmp *= SectorsPerCluster; // calculate sectorposition of new cluster |
ul_tmp += FirstDataCluster; // in relation to first datacluster of the disk. |
|
if(ul_tmp < 0xfff7) // has a new cluster been read or was the end of the fat reached? |
File->Cache[File->ByteOfCurrSector] = c; // write databyte into the buffer. The byte will be written to the device at once |
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. |
File->Position++; // the actual positon within the file. |
File->ByteOfCurrSector++; // goto next byte in sector |
if(File->ByteOfCurrSector >= BYTES_PER_SECTOR) // if the end of this sector is reached yet |
{ // save the sector to the sd-card |
if(SD_SUCCESS != SDC_PutSector(File->SectorInCache, File->Cache)) |
{ |
file->cluster_pointer = (u32) ul_tmp; // continue reading the file at the beginning of new datacluster. |
retvalue = 1; // a new cluster was found. |
} |
return(EOF); |
} |
File->ByteOfCurrSector = 0; // reset byte location |
File->SectorOfCurrCluster++; // next sector |
if(File->SectorOfCurrCluster >= Partition.SectorsPerCluster)// if end of cluster is reached, the next datacluster has to be searched in the FAT. |
{ |
if(!GetNextCluster(File)) // Sets the clusterpointer of the file to the next datacluster. |
{ // if current cluster was the last cluster of the file |
if(!AppendCluster(File)) // append a new and free cluster at the end of the file. |
{ |
File->SectorOfCurrCluster--; // jump back to last sector of last cluster |
File->ByteOfCurrSector = BYTES_PER_SECTOR; // set byte location to 1 byte over sector len |
return(EOF); |
} |
} |
else // next cluster |
{ |
File->SectorOfCurrCluster = 0; // start reading new cluster at first sector of the cluster. |
} |
} |
} |
return(retvalue); |
return(0); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u16 FindNextFreeCluster(void) |
// |
// Description: This function looks in the FAT to find the next free datacluster |
// |
// Returnvalue: The function returns the adress of the next free cluster found within the fAT. |
//________________________________________________________________________________________________________________________________________ |
|
u16 FindNextFreeCluster(File_t *file) |
/****************************************************************************************************************************************/ |
/* Function: fread_(void *buffer, s32 size, s32 count, File *File); */ |
/* */ |
/* Description: This function reads count objects of the specified size */ |
/* from the actual position of the file to the specified buffer. */ |
/* */ |
/* Returnvalue: The function returns the number of objects (not bytes) read from the file. */ |
/****************************************************************************************************************************************/ |
u32 fread_(void *buffer, u32 size, u32 count, File_t *File) |
{ |
u32 fat_pointer = 0; // Pointer to the first sector of the FAT. |
u32 ul_tmp = 0; // temporary variable used to calculate a sectornumber. |
u16 fat_sector_offset = 0; // index to a sector within the FAT. |
u16 fat_entry = 0; // index to an fatentry within the actual sector (256 fatentries are possible within one sector). |
u16 free_cluster = 0; // a pointer to the first sector of the next free cluster. |
u32 object_cnt = 0; // count the number of objects read from the file. |
u32 object_size = 0; // count the number of bytes read from the actual object. |
u8 *pbuff = 0; // a pointer to the actual bufferposition. |
u8 success = 1; // no error occured during read operation to the file. |
s16 c; |
|
pbuff = (u8 *) buffer; // cast the void pointer to an u8 * |
|
fat_pointer = (u32) FileAllocationTable; // start searching for empty cluster at the beginning of the fat. |
// if the end of the fat is not reached yet and no free cluster has been found |
while((fat_sector_offset < SectorsPerFat) && (!free_cluster)) |
while((object_cnt < count) && success) |
{ |
ul_tmp = (u32) ((u32)fat_pointer + (u32)fat_sector_offset); |
SDC_GetSector((u32)ul_tmp,file->buffer); // read next sector of FAT. |
file->sector_in_buffer = ul_tmp; // remember the number of the sector in FileBuffer. |
Fat = (FatEntry_t *)file->buffer; |
for(fat_entry=0;fat_entry<256;fat_entry++) // look for an free cluster at all entries in this sector of the fat. |
object_size = size; |
while((size > 0) && success) |
{ |
if(Fat[fat_entry].next_cluster == 0x0000) // empty cluster found!! |
{ |
Fat[fat_entry].next_cluster = 0xffff; // mark this fat-entry as used and save it to the device. |
SDC_PutSector((u32)file->sector_in_buffer,file->buffer); |
free_cluster = fat_entry; // the relative position of the free cluster found in this sector of the FAT. |
free_cluster += (fat_sector_offset << 8); // calculate the absolute position of the free cluster in the FAT; |
fat_entry = 256; // terminate the search for a free cluster in this sector. |
c = fgetc_(File); |
if(c != EOF) |
{ |
*pbuff = (u8)c; // read a byte from the buffer to the opened file. |
pbuff++; |
size--; |
} |
else // error or end of file reached |
{ |
success = 0; |
} |
} |
fat_sector_offset++; |
} |
return(free_cluster); |
if(success) object_cnt++; |
} |
return(object_cnt); // return the number of objects succesfully read from the file |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u16 AppendCluster(File *file); |
// |
// Description: This function finds the next free datacluster on the disk and appends it to the specified file. |
// |
// Returnvalue: This funktion returns 1 if a cluster was appended to the specified file. |
//________________________________________________________________________________________________________________________________________ |
|
u8 AppendCluster(File_t *file) |
/****************************************************************************************************************************************/ |
/* Function: fwrite_(void *buffer, s32 size, s32 count, File *file); */ |
/* */ |
/* Description: This function writes count objects of the specified size */ |
/* from the buffer pointer to the actual position in the file. */ |
/* */ |
/* Returnvalue: The function returns the number of objects (not bytes) read from the file. */ |
/****************************************************************************************************************************************/ |
u32 fwrite_(void *buffer, u32 size, u32 count, File_t *File) |
{ |
u16 free_cluster = 0; |
u32 fat_pointer = 0; |
u8 retvalue = 0; |
|
free_cluster = FindNextFreeCluster(file); // the next free cluster found on the disk. |
if(free_cluster) retvalue = 1; // A free cluster was found and can be added to the end of the file. |
fat_pointer = FileAllocationTable; // Set Pointer to the beginnig of the FAT. |
fat_pointer += (u32)((u32)GetFatClusterOffset(file) >> 8); // find the sector in the FAT with 256 entries per sector. |
|
SDC_GetSector(fat_pointer,file->buffer); |
Fat = (FatEntry_t *)file->buffer; |
Fat[GetFatSectorIndex(file)].next_cluster = free_cluster; // append the free cluster to the end of the file in the FAT. |
SDC_PutSector((u32)fat_pointer,file->buffer); // save the modified sector to the FAT. |
u32 object_cnt = 0; // count the number of objects written to the file. |
u32 object_size = 0; // count the number of bytes written from the actual object. |
u8 *pbuff = 0; // a pointer to the actual bufferposition. |
u8 success = 1; // no error occured during write operation to the file. |
s16 c; |
|
fat_pointer = (u32)free_cluster; |
fat_pointer -= 2; |
fat_pointer *= SectorsPerCluster; |
fat_pointer += FirstDataCluster; |
|
file->cluster_pointer = fat_pointer; // continue wrtiting to the file in the new and free datacluster. |
return(retvalue); // return 1 when a new cluster was appended to the file |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u16 GetFatClusterIndex(File *file); |
// |
// Description: This function returns the clusterindex of the cluster specified by file->cluster_pointer of the specified file. |
// |
//________________________________________________________________________________________________________________________________________ |
|
u16 GetFatClusterOffset(File_t *file) |
{ |
u32 fat_sector_offset = 0; |
|
fat_sector_offset = ((file->cluster_pointer) - (FirstDataCluster)); // Calculate index of actual cluster in FAT. |
fat_sector_offset /= SectorsPerCluster; |
fat_sector_offset += 2; // In Fat16 clusterpositions have an offset of two. |
pbuff = (u8 *) buffer; // cast the void pointer to an u8 * |
|
return((u16)fat_sector_offset); |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u16 GetFatSectorIndex(File *file); |
// |
// Description: This function returns the sectorindex of the cluster specified by file->cluster_pointer of the specified file. |
// |
//________________________________________________________________________________________________________________________________________ |
|
u16 GetFatSectorIndex(File_t *file) |
{ |
u16 fat_pointer = 0; |
while((object_cnt < count) && success) |
{ |
object_size = size; |
while((size > 0) && success) |
{ |
c = fputc_(*pbuff, File); // write a byte from the buffer to the opened file. |
if(c != EOF) |
{ |
pbuff++; |
size--; |
} |
else |
{ |
success = 0; |
} |
} |
if(success) object_cnt++; |
} |
|
fat_pointer = GetFatClusterOffset(file); |
fat_pointer = fat_pointer % 0x100; // Calculate the clusterposition in the fat |
|
return(fat_pointer); |
} |
return(object_cnt); // return the number of objects succesfully written to the file |
} |
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: u16 CreateDirectoryEntry(u8 *, u16, u8 attrib) |
// |
// Description: This function looks for the next free position in the directory and creates an entry. The type of an directoryentry is |
// specified by the attribute. |
// bit0: unused |
// bit1: archive |
// bit2: read_only |
// bit3: system |
// bit4: directory |
// bit5: volume |
//________________________________________________________________________________________________________________________________________ |
|
u8 CreateDirectoryEntry(u8 *fname, u16 cluster, File_t *file,u8 attrib) |
/****************************************************************************************************************************************/ |
/* Function: fputs_(const u8 *string, File_t *File); */ |
/* */ |
/* Description: This function writes a string to the specified file. */ |
/* */ |
/* Returnvalue: The function returns a no negative value or EOF on error. */ |
/****************************************************************************************************************************************/ |
s16 fputs_(const u8 *string, File_t *File) |
{ |
u16 rootentry = 0; // index to an entry in the rootdirectory. |
u16 cnt_enries_searched = 0; // count the number of rootentries which have been searched already. |
u8 i = 0; |
u16 sector_offset = 0; // index to the sector of the Rootentry which is searched momentarily |
u8 retvalue = 0; |
u8 i=0; |
s16 c = 0; |
|
// directory starts at sector specified by dir_sector. This can be the rootdirectory or any other directory. |
do |
{ // search the next 16 rootentries in this sector of the roordirectory. |
rootentry=0; |
SDC_GetSector((u32)(RootDirectory + sector_offset),file->buffer); // Read the Rootdirectory. |
DirectoryEntry = (DirEntry_t *)file->buffer; |
while((rootentry<16) && (!retvalue)) |
{ |
if((DirectoryEntry[rootentry].attribute == 0) || (DirectoryEntry[rootentry].attribute == 0xE5)) // empty directory entry found |
{ |
for(i=0;i<11;i++) DirectoryEntry[rootentry].name[i] = fname[i]; // Kopie the filename and the file extension to the directoryentry. |
DirectoryEntry[rootentry].attribute = attrib; // Set the fileattribute to archive to reserve the directoryentry. |
DirectoryEntry[rootentry].startcluster = cluster; // copy the location of the first datacluster to the directoryentry. |
DirectoryEntry[rootentry].size = 0; // the new createted file has no content yet. |
file->directory_sector = (u32) (RootDirectory + sector_offset); |
file->directory_index = (u8) rootentry; |
retvalue = 1; |
SDC_PutSector((u32)(RootDirectory + sector_offset),file->buffer); |
} |
rootentry++; |
cnt_enries_searched++; |
} |
if(!retvalue) // file not found in this sector so take next sector. |
{ |
rootentry = 0; |
sector_offset++; |
} |
while((string[i] != 0)&& (c != EOF)) |
{ |
c = fputc_(string[i], File); |
i++; |
} |
while((cnt_enries_searched< PossibleRootEntries) && (!retvalue)); |
|
return(retvalue); // return 1 if file has been created otherwise return 0. |
return(c); |
} |
|
|
|
|
//________________________________________________________________________________________________________________________________________ |
// Funtion: void SeperateFileName(u8*); |
// |
// Description: This function seperates the filename and the fileattribute and brings them into the needed format ('test.txt' -> 'TEST TXT'); |
// |
//________________________________________________________________________________________________________________________________________ |
|
void SeperateFileName(u8 *fname, u8 *name) |
/****************************************************************************************************************************************/ |
/* Function: fgets_(u8 *, s16 , File_t *); */ |
/* */ |
/* Description: This function reads a string from the file to the specifies string. */ |
/* */ |
/* Returnvalue: A pointer to the string read from the file or 0 on error. */ |
/****************************************************************************************************************************************/ |
u8 * fgets_(u8 *string, s16 length, File_t *File) |
{ |
u8 readpointer = 0; |
u8 writepointer = 0; |
u8 dircnt = 0; // the number of subdirectories found in filepath. |
u8 fileindex = 0; // the position in the filenamestring where the last "/" is found. |
u8 *pbuff; |
s16 c = 0; |
|
while(fname[readpointer]!=0) // search the string until the end is reached. |
if((File == 0) || (string == 0) || (length = 0)) return (0); |
pbuff = string; |
while(length > 1) // read the count-1 characters from the file to the string. |
{ |
if((fname[readpointer] == '/') && readpointer) // subdirectory found. ignore first "/" as directory. |
c = fgetc_(File); // read a character from the opened file. |
switch(c) |
{ |
dircnt++; // subdirectory entry found. |
fileindex = (readpointer + 1); // store the index of the last slash found as the beginning of the filename. |
case 0x0A: |
c = 0; // set string terminator |
length = 1; // stop loop |
break; |
|
case EOF: |
c = 0; // set string terminator |
length = 1; // stop loop |
break; |
} |
readpointer++; |
*pbuff = (u8)c; // copy byte to string |
length--; |
pbuff++; |
} |
readpointer = fileindex; // start seperating the filename from the directory at the stored position. |
dircnt = 0; |
return(string); |
} |
|
while((writepointer<=10) && (fname[readpointer]!=0)) // the rootdirectoryentry is 8bytes for filename and 3bytes for fileattribute. |
{ // the filename in the rootdirectory is in the format "TEST TXT" without the dot. |
if(fname[readpointer]=='.') // seperating filename and attribute. |
{ |
readpointer++; |
writepointer=8; |
} |
else |
{ |
if((fname[readpointer]>96) && (fname[readpointer]<123)) |
{ |
name[writepointer]=(fname[readpointer] - 32); // all characters must be upper case. |
} |
else |
{ |
name[writepointer]=fname[readpointer]; |
} |
readpointer++; |
writepointer++; |
} |
} |
} |
|