File SDClass::open(const char *filepath, uint8_t mode) { /* Open the supplied file path for reading or writing. The file content can be accessed via the `file` property of the `SDClass` object--this property is currently a standard `SdFile` object from `sdfatlib`. Defaults to read only. If `write` is true, default action (when `append` is true) is to append data to the end of the file. If `append` is false then the file will be truncated first. If the file does not exist and it is opened for writing the file will be created. An attempt to open a file for reading that does not exist is an error. */ int pathidx; // do the interative search SdFile parentdir = getParentDir(filepath, &pathidx); // no more subdirs! filepath += pathidx; if (! filepath[0]) { // it was the directory itself! return File(parentdir, "/"); } // Open the file itself SdFile file; // failed to open a subdir! if (!parentdir.isOpen()) return File(); // there is a special case for the Root directory since its a static dir if (parentdir.isRoot()) { if ( ! file.open(SD.root, filepath, mode)) { // failed to open the file :( return File(); } // dont close the root! } else { if ( ! file.open(parentdir, filepath, mode)) { return File(); } // close the parent parentdir.close(); } if (mode & O_APPEND & O_WRITE) file.seekSet(file.fileSize()); return File(file, filepath); }
void CardReader::removeFile(char* name) { if(!cardOK) return; file.close(); sdprinting = false; SdFile myDir; curDir=&root; char *fname=name; char *dirname_start,*dirname_end; if(name[0]=='/') { dirname_start=strchr(name,'/')+1; while(dirname_start>0) { dirname_end=strchr(dirname_start,'/'); //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name)); //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name)); if(dirname_end>0 && dirname_end>dirname_start) { char subdirname[13]; strncpy(subdirname, dirname_start, dirname_end-dirname_start); subdirname[dirname_end-dirname_start]=0; SERIAL_ECHOLN(subdirname); if(!myDir.open(curDir,subdirname,O_READ)) { SERIAL_PROTOCOLPGM("open failed, File: "); SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOLLNPGM("."); return; } else { //SERIAL_ECHOLN("dive ok"); } curDir=&myDir; dirname_start=dirname_end+1; } else // the reminder after all /fsa/fdsa/ is the filename { fname=dirname_start; //SERIAL_ECHOLN("remaider"); //SERIAL_ECHOLN(fname); break; } } } else //relative path { curDir=&workDir; } if (file.remove(curDir, fname)) { SERIAL_PROTOCOLPGM("File deleted:"); SERIAL_PROTOCOL(fname); sdpos = 0; } else { SERIAL_PROTOCOLPGM("Deletion failed, File: "); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } }
void CardReader::lsDive(const char *prepend,SdFile parent) { dir_t p; uint8_t cnt=0; while (parent.readDir(p, longFilename) > 0) { if( DIR_IS_SUBDIR(&p) && lsAction!=LS_Count && lsAction!=LS_GetFilename) // hence LS_SerialPrint { char path[13*2]; char lfilename[13]; createFilename(lfilename,p); path[0]=0; if(strlen(prepend)==0) //avoid leading / if already in prepend { strcat(path,"/"); } strcat(path,prepend); strcat(path,lfilename); strcat(path,"/"); //Serial.print(path); SdFile dir; if(!dir.open(parent,lfilename, O_READ)) { if(lsAction==LS_SerialPrint) { SERIAL_ECHO_START; SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR); SERIAL_ECHOLN(lfilename); } } lsDive(path,dir); //close done automatically by destructor of SdFile } else { if (p.name[0] == DIR_NAME_FREE) break; if (p.name[0] == DIR_NAME_DELETED || p.name[0] == '.'|| p.name[0] == '_') continue; if (longFilename[0] != '\0' && (longFilename[0] == '.' || longFilename[0] == '_')) continue; if ( p.name[0] == '.') { if ( p.name[1] != '.') continue; } if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; filenameIsDir=DIR_IS_SUBDIR(&p); if(!filenameIsDir) { if(p.name[8]!='G') continue; if(p.name[9]=='~') continue; } //if(cnt++!=nr) continue; createFilename(filename,p); if(lsAction==LS_SerialPrint) { SERIAL_PROTOCOL(prepend); SERIAL_PROTOCOLLN(filename); } else if(lsAction==LS_Count) { nrFiles++; } else if(lsAction==LS_GetFilename) { if(cnt==nrFiles) return; cnt++; } } } }
void CardReader::openFile(char* name,bool read) { if(!cardOK) return; file.close(); sdprinting = false; SdFile myDir; curDir=&root; char *fname=name; char *dirname_start,*dirname_end; if(name[0]=='/') { dirname_start=strchr(name,'/')+1; while(dirname_start>0) { dirname_end=strchr(dirname_start,'/'); //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name)); //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name)); if(dirname_end>0 && dirname_end>dirname_start) { char subdirname[13]; strncpy(subdirname, dirname_start, dirname_end-dirname_start); subdirname[dirname_end-dirname_start]=0; SERIAL_ECHOLN(subdirname); if(!myDir.open(curDir,subdirname,O_READ)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOLLNPGM("."); return; } else { //SERIAL_ECHOLN("dive ok"); } curDir=&myDir; dirname_start=dirname_end+1; } else // the reminder after all /fsa/fdsa/ is the filename { fname=dirname_start; //SERIAL_ECHOLN("remaider"); //SERIAL_ECHOLN(fname); break; } } } else //relative path { curDir=&workDir; } if(read) { if (file.open(curDir, fname, O_READ)) { filesize = file.fileSize(); SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLPGM(MSG_SD_SIZE); SERIAL_PROTOCOLLN(filesize); sdpos = 0; SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED); lcd_setstatus(fname); } else { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } } else { //write if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } else { saving = true; SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE); SERIAL_PROTOCOLLN(name); lcd_setstatus(fname); } } }
void CardReader::openFile(char* name,bool read, bool replace_current/*=true*/) { if(!cardOK) return; if(file.isOpen()) //replacing current file by new file, or subfile call { if(!replace_current) { if((int)file_subcall_ctr>(int)SD_PROCEDURE_DEPTH-1) { SERIAL_ERROR_START; SERIAL_ERRORPGM("trying to call sub-gcode files with too many levels. MAX level is:"); SERIAL_ERRORLN(SD_PROCEDURE_DEPTH); kill(); return; } SERIAL_ECHO_START; SERIAL_ECHOPGM("SUBROUTINE CALL target:\""); SERIAL_ECHO(name); SERIAL_ECHOPGM("\" parent:\""); //store current filename and position getAbsFilename(filenames[file_subcall_ctr]); SERIAL_ECHO(filenames[file_subcall_ctr]); SERIAL_ECHOPGM("\" pos"); SERIAL_ECHOLN(sdpos); filespos[file_subcall_ctr]=sdpos; file_subcall_ctr++; } else { SERIAL_ECHO_START; SERIAL_ECHOPGM("Now doing file: "); SERIAL_ECHOLN(name); } file.close(); } else //opening fresh file { file_subcall_ctr=0; //resetting procedure depth in case user cancels print while in procedure SERIAL_ECHO_START; SERIAL_ECHOPGM("Now fresh file: "); SERIAL_ECHOLN(name); } sdprinting = false; SdFile myDir; curDir=&root; char *fname=name; char *dirname_start,*dirname_end; if(name[0]=='/') { dirname_start=strchr(name,'/')+1; while(dirname_start>0) { dirname_end=strchr(dirname_start,'/'); //SERIAL_ECHO("start:");SERIAL_ECHOLN((int)(dirname_start-name)); //SERIAL_ECHO("end :");SERIAL_ECHOLN((int)(dirname_end-name)); if(dirname_end>0 && dirname_end>dirname_start) { char subdirname[13]; strncpy(subdirname, dirname_start, dirname_end-dirname_start); subdirname[dirname_end-dirname_start]=0; SERIAL_ECHOLN(subdirname); if(!myDir.open(curDir,subdirname,O_READ)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(subdirname); SERIAL_PROTOCOLLNPGM("."); return; } else { //SERIAL_ECHOLN("dive ok"); } curDir=&myDir; dirname_start=dirname_end+1; } else // the reminder after all /fsa/fdsa/ is the filename { fname=dirname_start; //SERIAL_ECHOLN("remaider"); //SERIAL_ECHOLN(fname); break; } } } else //relative path { curDir=&workDir; } if(read) { if (file.open(curDir, fname, O_READ)) { filesize = file.fileSize(); SERIAL_PROTOCOLPGM(MSG_SD_FILE_OPENED); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLPGM(MSG_SD_SIZE); SERIAL_PROTOCOLLN(filesize); sdpos = 0; SERIAL_PROTOCOLLNPGM(MSG_SD_FILE_SELECTED); lcd_setstatus(fname); } else { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } } else { //write if (!file.open(curDir, fname, O_CREAT | O_APPEND | O_WRITE | O_TRUNC)) { SERIAL_PROTOCOLPGM(MSG_SD_OPEN_FILE_FAIL); SERIAL_PROTOCOL(fname); SERIAL_PROTOCOLLNPGM("."); } else { saving = true; SERIAL_PROTOCOLPGM(MSG_SD_WRITE_TO_FILE); SERIAL_PROTOCOLLN(name); lcd_setstatus(fname); } } }
void setup() { Serial.begin(BPS_115200); Serial.println("> type any char to start"); while (!Serial.available()); Serial.println(); if (!card.init(SPI_HALF_SPEED)) Serial.println("> card.init failed"); else Serial.println("> card.init passed"); // spi.end(); SD_SPI.begin(SPI_HIGH_CLOCK, MSBFIRST, 0); delay(100); // initialize a FAT volume if (!volume.init(&card,1)) Serial.println("> volume.init failed"); else Serial.println("> volume.init passed"); // open the root directory if (!root.openRoot(&volume)) Serial.println("> openRoot failed"); else Serial.println("> openRoot passed"); // open a file if (file.open(&root, "Read.txt", O_READ)) { Serial.println("> Opened Read.txt"); Serial.println("> Reading ..."); Serial.println(); for(int i=0; i<15; i++) Serial.print((char)file.read()); Serial.println(""); } else { Serial.println("file.open failed"); } Serial.println(); Serial.println("> Reading remained data..."); Serial.println(); int16_t n; uint8_t buf[7];// nothing special about 7, just a lucky number. while ((n = file.read(buf, sizeof(buf))) > 0) { for (uint8_t i = 0; i < n; i++) Serial.print((char)buf[i]); } /* easier way int16_t c; while ((c = file.read()) > 0) Serial.print((char)c); */ file.close(); Serial.println("\n> Done"); SD_SPI.end(); }
void setup() { Serial.begin(BPS_115200); PgmPrintln("Type any character to start"); while (!Serial.available()); // PgmPrint("Free RAM: "); /// Serial.println(FreeRam()); // initialize the SD card at SPI_FULL_SPEED for best performance. // try SPI_HALF_SPEED if bus errors occur. if (!card.init(SPI_FULL_SPEED)) error("card.init failed"); // initialize a FAT volume if (!volume.init(&card)) error("volume.init failed!"); PgmPrint("Type is FAT"); Serial.println(volume.fatType(), DEC); if (!root.openRoot(&volume)) error("openRoot failed"); // open or create file - truncate existing file. if (!file.open(&root, "BENCH.DAT", O_CREAT | O_TRUNC | O_RDWR)) { error("open failed"); } // fill buf with known data for (uint16_t i = 0; i < (BUF_SIZE-2); i++) { buf[i] = 'A' + (i % 26); } buf[BUF_SIZE-2] = '\r'; buf[BUF_SIZE-1] = '\n'; PgmPrint("File size "); Serial.print(FILE_SIZE_MB); PgmPrintln(" MB"); PgmPrintln("Starting write test. Please wait up to a minute"); // do write test uint32_t n = FILE_SIZE/sizeof(buf); uint32_t t = millis(); for (uint32_t i = 0; i < n; i++) { if (file.write(buf, sizeof(buf)) != sizeof(buf)) { error("write failed"); } } t = millis() - t; file.sync(); double r = (double)file.fileSize()/t; PgmPrint("Write "); Serial.print(r); PgmPrintln(" KB/sec"); Serial.println(); PgmPrintln("Starting read test. Please wait up to a minute"); // do read test file.rewind(); t = millis(); for (uint32_t i = 0; i < n; i++) { if (file.read(buf, sizeof(buf)) != sizeof(buf)) { error("read failed"); } } t = millis() - t; r = (double)file.fileSize()/t; PgmPrint("Read "); Serial.print(r); PgmPrintln(" KB/sec"); PgmPrintln("Done"); }
void writeGPSLog(uint32_t gpstime, int32_t latitude, int32_t longitude, int32_t altitude) { #else void writeGPSLog(int32_t latitude, int32_t longitude, int32_t altitude) { #endif if (f.SDCARD == 0) return; if (gps_data.open(GPS_LOG_FILENAME, O_WRITE | O_CREAT | O_APPEND)) { #ifdef UBLOX gps_data.print(gpstime); gps_data.write(','); #endif gps_data.print(latitude); gps_data.write(','); gps_data.print(longitude); gps_data.write(','); gps_data.print(altitude); gps_data.println(); gps_data.close(); } else { return; } } void writePLogToSD() { if (f.SDCARD == 0) return; plog.checksum = calculate_sum((uint8_t*)&plog, sizeof(plog)); if (permanent.open(PERMANENT_LOG_FILENAME, O_WRITE | O_CREAT | O_TRUNC)) { permanent.print(F("arm=")); permanent.println(plog.arm); permanent.print(F("disarm=")); permanent.println(plog.disarm); permanent.print(F("start=")); permanent.println(plog.start); permanent.print(F("armed_time=")); permanent.println(plog.armed_time); permanent.print(F("lifetime=")); permanent.println(plog.lifetime, DEC); permanent.print(F("failsafe=")); permanent.println(plog.failsafe); permanent.print(F("i2c=")); permanent.println(plog.i2c); permanent.print(F("running=")); permanent.println(plog.running, DEC); permanent.print(F("checksum=")); permanent.println(plog.checksum, DEC); permanent.print(F("debug=")); permanent.print(debug[0]); permanent.print(F(",")); permanent.print(debug[1]); permanent.print(F(",")); permanent.print(debug[2]); permanent.print(F(",")); permanent.println(debug[3]); permanent.println(); permanent.close(); } else { return; } } void fillPlogStruct(char* key, char* value) { if (strcmp(key, "arm") == 0) sscanf(value, "%u", &plog.arm); if (strcmp(key, "disarm") == 0) sscanf(value, "%u", &plog.disarm); if (strcmp(key, "start") == 0) sscanf(value, "%u", &plog.start); if (strcmp(key, "armed_time") == 0) sscanf(value, "%lu", &plog.armed_time); if (strcmp(key, "lifetime") == 0) sscanf(value, "%lu", &plog.lifetime); if (strcmp(key, "failsafe") == 0) sscanf(value, "%u", &plog.failsafe); if (strcmp(key, "i2c") == 0) sscanf(value, "%u", &plog.i2c); if (strcmp(key, "running") == 0) sscanf(value, "%hhu", &plog.running); if (strcmp(key, "checksum") == 0) sscanf(value, "%hhu", &plog.checksum); } void readPLogFromSD() { if (f.SDCARD == 0) return; SdFile myfile; char key[12]; char value[32]; char* tabPtr = key; int c; uint8_t i = 0; if (myfile.open(PERMANENT_LOG_FILENAME, O_READ)) { while (myfile.available()) { c = myfile.read(); switch ((char)c) { case ' ': break; case '=': *tabPtr = '\0'; tabPtr = value; break; case '\n': *tabPtr = '\0'; tabPtr = key; i = 0; fillPlogStruct(key, value); memset(key, '\0', sizeof(key)); memset(value, '\0', sizeof(value)); break; default: i++; if (i <= 12) { *tabPtr = (char)c; tabPtr++; } break; } } } else return; if (calculate_sum((uint8_t*)&plog, sizeof(plog)) != plog.checksum) { #if defined(BUZZER) alarmArray[7] = 3; blinkLED(9, 100, 3); #endif // force load defaults plog.arm = plog.disarm = plog.start = plog.failsafe = plog.i2c = 11; plog.running = 1; plog.lifetime = plog.armed_time = 3; writePLogToSD(); } }
/* * Setup */ void setup() { wdt_enable(WDTO_8S); wdt_reset(); //Setup Ports Serial.begin(115200); //Start Debug Serial 0 Serial1.begin(9600); //Start GPS Serial 1 Serial2.begin(9600); pinMode(PIN_LED_GREEN, OUTPUT); //Blue GREEN pinMode(PIN_LED_RED, OUTPUT); //Blue RED pinMode(PIN_LED_BLUE, OUTPUT); //Blue LED pinMode(PIN_SPI_CS,OUTPUT); //Chip Select Pin for the SD Card pinMode(10, OUTPUT); //SDcard library expect 10 to set set as output. // Initialise the GPS wdt_disable(); gps.init(); gps.configureUbloxSettings(); // Configure Ublox for MY_HIGH altitude mode wdt_enable(WDTO_8S); // join I2C bus //start I2C transfer to the Module/Transmitter Wire.begin(); //Set up the two EasyTransfer methods ETI2Cout.begin(details(mD.i2cOut), &Wire); //setup the data structure to transfer out ETSerialIn.begin(details(vals), &Serial2); //Start up the LGgyro if (LGgyro.init()) { #ifdef DEBUG_ON Serial.println("LGgyro OK"); #endif LGgyro.enableDefault(); } else { #ifdef DEBUG_ON Serial.println("LGgyro not working"); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,1000); //Red LED } //Start up the accelerometer accel = ADXL345(); // Create an instance of the accelerometer if(accel.EnsureConnected()) { // Check that the accelerometer is connected. #ifdef DEBUG_ON Serial.println("Connected to ADXL345."); #endif accel.SetRange(2, true); // Set the range of the accelerometer to a maximum of 2G. accel.EnableMeasurements(); // Tell the accelerometer to start taking measurements. } else{ #ifdef DEBUG_ON Serial.println("Could not connect to ADXL345."); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,2000); //Red LED } //Start up the compass compass = HMC5883L(); // Construct a new HMC5883 compass. #ifdef DEBUG_ON if(compass.EnsureConnected() == 1) { Serial.println("Connected to HMC5883L."); } else { Serial.println("Not Connected to HMC5883L."); } #endif error = compass.SetScale(1.3); // Set the scale of the compass. #ifdef DEBUG_ON if(error != 0) { // If there is an error, print it out. Serial.println("Compass Error 1"); Serial.println(compass.GetErrorText(error)); } else { Serial.println("Compass Ok 1"); } #endif error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode to Continuous #ifdef DEBUG_ON if(error != 0) { // If there is an error, print it out. Serial.println("Compass error 2"); Serial.println(compass.GetErrorText(error)); } else { Serial.println("Compass Ok 2"); } #endif //Start up the Pressure Sensor dps = BMP085(); dps.init(); #ifdef DEBUG_ON Serial.print("BMP Mode "); Serial.println(dps.getMode()); #endif wdt_reset(); // Start up the OneWire Sensors library and turn off blocking takes too long! sensors.begin(); sensors.setWaitForConversion(false); sensors.requestTemperaturesByAddress(outsideThermometer); // Send the command to get temperature //Initialise all of the record values mD.vals.tCount = 0; mD.vals.uslCount = 0; mD.vals.year = 0; mD.vals.month = 0; mD.vals.day = 0; mD.vals.hour = 0; mD.vals.minute = 0; mD.vals.second = 0; mD.vals.hundredths = 0; mD.vals.iLat = 0; mD.vals.iLong = 0; mD.vals.iAlt = 0; mD.vals.bSats = 0; mD.vals.iAngle = 0; mD.vals.iHspeed = 0; mD.vals.iVspeed = 0; mD.vals.age = 0; mD.vals.ihdop = 0; mD.vals.AcXPayload = 0; mD.vals.AcYPayload = 0; mD.vals.AcZPayload = 0; mD.vals.GyXPayload = 0; mD.vals.GyYPayload = 0; mD.vals.GyZPayload = 0; mD.vals.MgXPayload = 0; mD.vals.MgYPayload = 0; mD.vals.MgZPayload = 0; mD.vals.TmpPayload = 0; //Connect to the SD Card if(!SD.begin(PIN_SPI_CS, SPI_HALF_SPEED)) { #ifdef DEBUG_ON Serial.println("SD not working!!"); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,3000); //Red LED } else { #ifdef DEBUG_ON Serial.println("SD OK"); #endif dataFile.open(SD_LOG_FILE, O_CREAT | O_WRITE | O_APPEND); //Open Logfile if (!dataFile.isOpen()) { #ifdef DEBUG_ON Serial.println("SD Data File Not Opened"); #endif SET_LED_Status(SET_LED_WHITE,500); SET_LED_Status(SET_LED_RED,3000); } } //Cycle lights SET_LED_Status(SET_LED_OFF,0); SET_LED_Status(SET_LED_RED,500); SET_LED_Status(SET_LED_GREEN,500); SET_LED_Status(SET_LED_BLUE,500); SET_LED_Status(SET_LED_OFF,0); elapseSIM900 = millis(); //Elapse counter for data to SIM900 elapseNTXB = millis(); //Elapse counter for data to NTXB NEWGPSDATA = false; wdt_enable(WDTO_2S); wdt_reset(); }
//------------------------------------------------------------------------------ void setup() { Serial.begin(9600); // Wait for USB Serial while (!Serial) { SysCall::yield(); } delay(1000); cout << F("Type any character to start\n"); // Wait for input line and discard. cin.readline(); cout << endl; // Initialize the SD card at SPI_HALF_SPEED to avoid bus errors with // breadboards. use SPI_FULL_SPEED for better performance. if (!sd.begin(SD_CHIP_SELECT, SPI_HALF_SPEED)) { sd.initErrorHalt(); } if (sd.exists("Folder1") || sd.exists("Folder1/file1.txt") || sd.exists("Folder1/File2.txt")) { error("Please remove existing Folder1, file1.txt, and File2.txt"); } int rootFileCount = 0; sd.vwd()->rewind(); while (file.openNext(sd.vwd(), O_READ)) { if (!file.isHidden()) { rootFileCount++; } file.close(); if (rootFileCount > 10) { error("Too many files in root. Please use an empty SD."); } } if (rootFileCount) { cout << F("\nPlease use an empty SD for best results.\n\n"); delay(1000); } // Create a new folder. if (!sd.mkdir("Folder1")) { error("Create Folder1 failed"); } cout << F("Created Folder1\n"); // Create a file in Folder1 using a path. if (!file.open("Folder1/file1.txt", O_CREAT | O_WRITE)) { error("create Folder1/file1.txt failed"); } file.close(); cout << F("Created Folder1/file1.txt\n"); // Change volume working directory to Folder1. if (!sd.chdir("Folder1")) { error("chdir failed for Folder1.\n"); } cout << F("chdir to Folder1\n"); // Create File2.txt in current directory. if (!file.open("File2.txt", O_CREAT | O_WRITE)) { error("create File2.txt failed"); } file.close(); cout << F("Created File2.txt in current directory\n"); cout << F("\nList of files on the SD.\n"); sd.ls("/", LS_R); // Remove files from current directory. if (!sd.remove("file1.txt") || !sd.remove("File2.txt")) { error("remove failed"); } cout << F("\nfile1.txt and File2.txt removed.\n"); // Change current directory to root. if (!sd.chdir()) { error("chdir to root failed.\n"); } cout << F("\nList of files on the SD.\n"); sd.ls(LS_R); // Remove Folder1. if (!sd.rmdir("Folder1")) { error("rmdir for Folder1 failed\n"); } cout << F("\nFolder1 removed.\n"); cout << F("\nList of files on the SD.\n"); sd.ls(LS_R); cout << F("Done!\n"); }
uint32_t SDCard_FileHandler::fileSize(String file){ SdFile myFile; myFile.open(file); auto size = myFile.fileSize(); return size; }
/** * Dive into a folder and recurse depth-first to perform a pre-set operation lsAction: * LS_Count - Add +1 to nrFiles for every file within the parent * LS_GetFilename - Get the filename of the file indexed by nrFiles * LS_SerialPrint - Print the full path of each file to serial output */ void CardReader::lsDive(const char* prepend, SdFile parent, const char* const match/*=NULL*/) { dir_t p; uint8_t cnt = 0; // Read the next entry from a directory while (parent.readDir(p, longFilename) > 0) { // If the entry is a directory and the action is LS_SerialPrint if (DIR_IS_SUBDIR(&p) && lsAction != LS_Count && lsAction != LS_GetFilename) { // Get the short name for the item, which we know is a folder char lfilename[FILENAME_LENGTH]; createFilename(lfilename, p); // Allocate enough stack space for the full path to a folder, trailing slash, and nul boolean prepend_is_empty = (prepend[0] == '\0'); int len = (prepend_is_empty ? 1 : strlen(prepend)) + strlen(lfilename) + 1 + 1; char path[len]; // Append the FOLDERNAME12/ to the passed string. // It contains the full path to the "parent" argument. // We now have the full path to the item in this folder. strcpy(path, prepend_is_empty ? "/" : prepend); // root slash if prepend is empty strcat(path, lfilename); // FILENAME_LENGTH-1 characters maximum strcat(path, "/"); // 1 character // Serial.print(path); // Get a new directory object using the full path // and dive recursively into it. SdFile dir; if (!dir.open(parent, lfilename, O_READ)) { if (lsAction == LS_SerialPrint) { SERIAL_ECHO_START; SERIAL_ECHOLN(MSG_SD_CANT_OPEN_SUBDIR); SERIAL_ECHOLN(lfilename); } } lsDive(path, dir); // close() is done automatically by destructor of SdFile } else { char pn0 = p.name[0]; if (pn0 == DIR_NAME_FREE) break; if (pn0 == DIR_NAME_DELETED || pn0 == '.') continue; if (longFilename[0] == '.') continue; if (!DIR_IS_FILE_OR_SUBDIR(&p)) continue; filenameIsDir = DIR_IS_SUBDIR(&p); if (!filenameIsDir && (p.name[8] != 'G' || p.name[9] == '~')) continue; switch (lsAction) { case LS_Count: nrFiles++; break; case LS_SerialPrint: createFilename(filename, p); SERIAL_PROTOCOL(prepend); SERIAL_PROTOCOLLN(filename); break; case LS_GetFilename: createFilename(filename, p); if (match != NULL) { if (strcasecmp(match, filename) == 0) return; } else if (cnt == nrFiles) return; cnt++; break; } } } // while readDir }