mbed-os-examples / Mbed OS mbed-os-example-fat-filesystem
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "FATFileSystem.h"
00003 #include "HeapBlockDevice.h"
00004 #include <stdio.h>
00005 #include <errno.h>
00006 
00007 HeapBlockDevice bd(128 * 512, 512);
00008 FATFileSystem fs("fs");
00009 
00010 void return_error(int ret_val){
00011   if (ret_val)
00012     printf("Failure. %d\r\n", ret_val);
00013   else
00014     printf("done.\r\n");
00015 }
00016 
00017 void errno_error(void* ret_val){
00018   if (ret_val == NULL)
00019     printf(" Failure. %d \r\n", errno);
00020   else
00021     printf(" done.\r\n");
00022 }
00023 
00024 int main() {
00025   int error = 0;
00026   printf("Welcome to the filesystem example.\r\n"
00027          "Formatting a FAT, RAM-backed filesystem. ");
00028   error = FATFileSystem::format(&bd);
00029   return_error(error);
00030 
00031   printf("Mounting the filesystem on \"/fs\". ");
00032   error = fs.mount(&bd);
00033   return_error(error);
00034 
00035   printf("Opening a new file, numbers.txt.");
00036   FILE* fd = fopen("/fs/numbers.txt", "w");
00037   errno_error(fd);
00038 
00039   for (int i = 0; i < 20; i++){
00040     printf("Writing decimal numbers to a file (%d/20)\r", i);
00041     fprintf(fd, "%d\r\n", i);
00042   }
00043   printf("Writing decimal numbers to a file (20/20) done.\r\n");
00044 
00045   printf("Closing file.");
00046   fclose(fd);
00047   printf(" done.\r\n");
00048 
00049   printf("Re-opening file read-only.");
00050   fd = fopen("/fs/numbers.txt", "r");
00051   errno_error(fd);
00052 
00053   printf("Dumping file to screen.\r\n");
00054   char buff[16] = {0};
00055   while (!feof(fd)){
00056     int size = fread(&buff[0], 1, 15, fd);
00057     fwrite(&buff[0], 1, size, stdout);
00058   }
00059   printf("EOF.\r\n");
00060 
00061   printf("Closing file.");
00062   fclose(fd);
00063   printf(" done.\r\n");
00064 
00065   printf("Opening root directory.");
00066   DIR* dir = opendir("/fs/");
00067   errno_error(fd);
00068 
00069   struct dirent* de;
00070   printf("Printing all filenames:\r\n");
00071   while((de = readdir(dir)) != NULL){
00072     printf("  %s\r\n", &(de->d_name)[0]);
00073   }
00074 
00075   printf("Closing root directory. ");
00076   error = closedir(dir);
00077   return_error(error);
00078   printf("Filesystem Demo complete.\r\n");
00079 
00080   while (true) {}
00081 }
00082