mFS file system library for EEPROM memory chips.

Revision:
13:142b6be3e3c8
Parent:
12:928346513c87
--- a/mfs.cpp	Thu Feb 24 00:02:36 2011 +0000
+++ b/mfs.cpp	Thu Feb 24 09:28:32 2011 +0000
@@ -129,18 +129,19 @@
     if(getNextFreeBlock(&fb) != 0)
         return 2; // Out of space
     
-    char cData[RB+20];
-    cData[0] = '\xCC';  // Necessary flags for a file
-    cData[1] = '\0';    // Only this block yet
+    char cData[RB+20+1];
+    cData[0] = '\xCC';   // Necessary flags for a file
+    cData[1] = '\0';     // No more blocks yet
     cData[2] = '\0';
-    cData[3] = '\0';    // First block there could't be prev blocks
+    cData[3] = '\0';     // First block so there is no prev blocks
     cData[4] = '\0';
+    cData[RB+20] = mEOF; // Set EOF at the begining
     
     for (char i=0; i < 20; i++)
         cData[RB+i] = filename[i];
     
     // Create file
-    write(cData, fb, 0, RB+20);
+    write(cData, fb, 0, RB+20+1);
         
     return 0;
 }
@@ -429,6 +430,13 @@
     
     for (i=0; i < n; i++)
     {
+        // If this is empty file EOF will be at first byte
+        fs->read(cData, currBlock, blockPos, 1);
+        if (cData[0] == mEOF)
+        {
+            return 1;
+        }
+        
         blockPos++;
         byteCount++;
     
@@ -566,6 +574,10 @@
     bool destructiveFlag = false; // Set this true if there is any data to be removed
     uint32_t destructiveBlock=0;  // First block to be removed by DWRITE
     
+    static bool fEOFow = false;   /* END of file found while appending (and overwritten).
+                                     Must be static because we don't want to found many EOF's. */
+    
+    
     if (bufPos == 0) return 0; // File up-to date
     if (fMode == RO) return 1;
     
@@ -625,14 +637,23 @@
             }
         }
         
+        if (fMode == AWRITE) // Check if EOF is here
+        {
+            fs->read(c, currBlock, blockPos, 1);
+            if ((c[0] == mEOF) && (fEOFow == false))
+                fEOFow = true;
+        }
+        
         // Write file
         c[0]=buffer[i];
         fs->write(c, currBlock, blockPos, 1);
         blockPos++;
         byteCount++;
+        
+        // For fail safe, write EOF now
+        if ((fMode == DWRITE)||(fEOFow == true))
+            fs->write((char[]){mEOF}, currBlock, blockPos, 1); // Write mEOF
     }
-    // Write mEOF
-    fs->write((char[]){mEOF}, currBlock, blockPos+1, 1);
     
     bufPos = 0; // Reset buffer position counter