-
Notifications
You must be signed in to change notification settings - Fork 0
/
SdFat.cpp
4525 lines (4253 loc) · 128 KB
/
SdFat.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Arduino SdFat Library
* Copyright (C) 2012 by William Greiman
*
* This file is part of the Arduino SdFat Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdFat Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "Repetier.h"
#if SDSUPPORT
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#define COMPAT_PRE1
#endif
//#include <SdFat.h>
extern int8_t RFstricmp(const char* s1, const char* s2);
extern int8_t RFstrnicmp(const char* s1, const char* s2, size_t n);
//#define GLENN_DEBUG
//------------------------------------------------------------------------------
static void pstrPrintln(FSTRINGPARAM(str)) {
Com::printFLN(str);
}
//------------------------------------------------------------------------------
/**
* Initialize an SdFat object.
*
* Initializes the SD card, SD volume, and root directory.
*
* \param[in] chipSelectPin SD chip select pin. See Sd2Card::init().
* \param[in] sckRateID value for SPI SCK rate. See Sd2Card::init().
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::begin(uint8_t chipSelectPin, uint8_t sckRateID) {
return card_.init(sckRateID, chipSelectPin) && vol_.init(&card_) && chdir(1);
}
//------------------------------------------------------------------------------
/** Change a volume's working directory to root
*
* Changes the volume's working directory to the SD's root directory.
* Optionally set the current working directory to the volume's
* working directory.
*
* \param[in] set_cwd Set the current working directory to this volume's
* working directory if true.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::chdir(bool set_cwd) {
if (set_cwd) SdBaseFile::cwd_ = &vwd_;
if (vwd_.isOpen()) vwd_.close();
return vwd_.openRoot(&vol_);
}
//------------------------------------------------------------------------------
/** Change a volume's working directory
*
* Changes the volume working directory to the \a path subdirectory.
* Optionally set the current working directory to the volume's
* working directory.
*
* Example: If the volume's working directory is "/DIR", chdir("SUB")
* will change the volume's working directory from "/DIR" to "/DIR/SUB".
*
* If path is "/", the volume's working directory will be changed to the
* root directory
*
* \param[in] path The name of the subdirectory.
*
* \param[in] set_cwd Set the current working directory to this volume's
* working directory if true.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::chdir(const char *path, bool set_cwd) {
SdBaseFile dir;
if (path[0] == '/' && path[1] == '\0') return chdir(set_cwd);
if (!dir.open(&vwd_, path, O_READ)) goto fail;
if (!dir.isDir()) goto fail;
vwd_ = dir;
if (set_cwd) SdBaseFile::cwd_ = &vwd_;
return true;
fail:
return false;
}
//------------------------------------------------------------------------------
/** Set the current working directory to a volume's working directory.
*
* This is useful with multiple SD cards.
*
* The current working directory is changed to this volume's working directory.
*
* This is like the Windows/DOS \<drive letter>: command.
*/
void SdFat::chvol() {
SdBaseFile::cwd_ = &vwd_;
}
//------------------------------------------------------------------------------
/** %Print any SD error code and halt. */
void SdFat::errorHalt() {
errorPrint();
while (1);
}
//------------------------------------------------------------------------------
/** %Print msg, any SD error code, and halt.
*
* \param[in] msg Message to print.
*/
void SdFat::errorHalt(char const* msg) {
errorPrint(msg);
while (1);
}
//------------------------------------------------------------------------------
/** %Print msg, any SD error code, and halt.
*
* \param[in] msg Message in program space (flash memory) to print.
*/
void SdFat::errorHalt_P(FSTRINGPARAM(msg)) {
errorPrint_P(msg);
while (1);
}
//------------------------------------------------------------------------------
/** %Print any SD error code. */
void SdFat::errorPrint() {
if (!card_.errorCode()) return;
Com::printFLN(Com::tSDErrorCode,card_.errorCode());
}
//------------------------------------------------------------------------------
/** %Print msg, any SD error code.
*
* \param[in] msg Message to print.
*/
void SdFat::errorPrint(char const* msg) {
Com::printFLN(Com::tError,msg);
errorPrint();
}
//------------------------------------------------------------------------------
/** %Print msg, any SD error code.
*
* \param[in] msg Message in program space (flash memory) to print.
*/
void SdFat::errorPrint_P(FSTRINGPARAM(msg)) {
Com::printF(Com::tError);
Com::printFLN(msg);
errorPrint();
}
//------------------------------------------------------------------------------
/**
* Test for the existence of a file.
*
* \param[in] name Name of the file to be tested for.
*
* \return true if the file exists else false.
*/
bool SdFat::exists(const char* name) {
return vwd_.exists(name);
}
//------------------------------------------------------------------------------
/** %Print error details and halt after SdFat::init() fails. */
void SdFat::initErrorHalt() {
initErrorPrint();
while (1);
}
//------------------------------------------------------------------------------
/**Print message, error details, and halt after SdFat::init() fails.
*
* \param[in] msg Message to print.
*/
void SdFat::initErrorHalt(char const *msg) {
Com::print(msg);
Com::println();
initErrorHalt();
}
//------------------------------------------------------------------------------
/**Print message, error details, and halt after SdFat::init() fails.
*
* \param[in] msg Message in program space (flash memory) to print.
*/
void SdFat::initErrorHalt_P(FSTRINGPARAM(msg)) {
pstrPrintln(msg);
initErrorHalt();
}
//------------------------------------------------------------------------------
/** Print error details after SdFat::init() fails. */
void SdFat::initErrorPrint() {
if (card_.errorCode()) {
pstrPrintln(PSTR("Can't access SD card. Do not reformat."));
if (card_.errorCode() == SD_CARD_ERROR_CMD0) {
pstrPrintln(PSTR("No card, wrong chip select pin, or SPI problem?"));
}
errorPrint();
} else if (vol_.fatType() == 0) {
pstrPrintln(PSTR("Invalid format, reformat SD."));
} else if (!vwd_.isOpen()) {
pstrPrintln(PSTR("Can't open root directory."));
} else {
pstrPrintln(PSTR("No error found."));
}
}
//------------------------------------------------------------------------------
/**Print message and error details and halt after SdFat::init() fails.
*
* \param[in] msg Message to print.
*/
void SdFat::initErrorPrint(char const *msg) {
Com::print(msg);
Com::println();
initErrorPrint();
}
//------------------------------------------------------------------------------
/**Print message and error details after SdFat::init() fails.
*
* \param[in] msg Message in program space (flash memory) to print.
*/
void SdFat::initErrorPrint_P(FSTRINGPARAM(msg)) {
pstrPrintln(msg);
initErrorHalt();
}
//------------------------------------------------------------------------------
/** Make a subdirectory in the volume working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for the subdirectory.
*
* \param[in] pFlag Create missing parent directories if true.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::mkdir(const char* path, bool pFlag) {
SdBaseFile sub;
return sub.mkdir(&vwd_, path, pFlag);
}
//------------------------------------------------------------------------------
/** Remove a file from the volume working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for the file.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::remove(const char* path) {
return SdBaseFile::remove(&vwd_, path);
}
//------------------------------------------------------------------------------
/** Rename a file or subdirectory.
*
* \param[in] oldPath Path name to the file or subdirectory to be renamed.
*
* \param[in] newPath New path name of the file or subdirectory.
*
* The \a newPath object must not exist before the rename call.
*
* The file to be renamed must not be open. The directory entry may be
* moved and file system corruption could occur if the file is accessed by
* a file object that was opened before the rename() call.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::rename(const char *oldPath, const char *newPath) {
SdBaseFile file;
if (!file.open(oldPath, O_READ)) return false;
return file.rename(&vwd_, newPath);
}
//------------------------------------------------------------------------------
/** Remove a subdirectory from the volume's working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for the subdirectory.
*
* The subdirectory file will be removed only if it is empty.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdFat::rmdir(const char* path) {
SdBaseFile sub;
if (!sub.open(path, O_READ)) return false;
return sub.rmdir();
}
//------------------------------------------------------------------------------
/** Truncate a file to a specified length. The current file position
* will be maintained if it is less than or equal to \a length otherwise
* it will be set to end of file.
*
* \param[in] path A path with a valid 8.3 DOS name for the file.
* \param[in] length The desired length for the file.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include file is read only, file is a directory,
* \a length is greater than the current file size or an I/O error occurs.
*/
bool SdFat::truncate(const char* path, uint32_t length) {
SdBaseFile file;
if (!file.open(path, O_WRITE)) return false;
return file.truncate(length);
}
// macro for debug
#define DBG_FAIL_MACRO // Serial.println(__LINE__)
//------------------------------------------------------------------------------
// pointer to cwd directory
SdBaseFile* SdBaseFile::cwd_ = 0;
// callback function for date/time
void (*SdBaseFile::dateTime_)(uint16_t* date, uint16_t* time) = 0;
//------------------------------------------------------------------------------
// add a cluster to a file
bool SdBaseFile::addCluster() {
if (!vol_->allocContiguous(1, &curCluster_)) {
DBG_FAIL_MACRO;
goto fail;
}
// if first cluster of file link to directory entry
if (firstCluster_ == 0) {
firstCluster_ = curCluster_;
flags_ |= F_FILE_DIR_DIRTY;
}
return true;
fail:
return false;
}
//------------------------------------------------------------------------------
// Add a cluster to a directory file and zero the cluster.
// return with first block of cluster in the cache
cache_t* SdBaseFile::addDirCluster() {
uint32_t block;
cache_t* pc;
// max folder size
if (fileSize_/sizeof(dir_t) >= 0XFFFF) {
DBG_FAIL_MACRO;
goto fail;
}
if (!addCluster()) {
DBG_FAIL_MACRO;
goto fail;
}
block = vol_->clusterStartBlock(curCluster_);
pc = vol_->cacheFetch(block, SdVolume::CACHE_RESERVE_FOR_WRITE);
if (!pc) {
DBG_FAIL_MACRO;
goto fail;
}
memset(pc, 0, 512);
// zero rest of clusters
for (uint8_t i = 1; i < vol_->blocksPerCluster_; i++) {
if (!vol_->writeBlock(block + i, pc->data)) {
DBG_FAIL_MACRO;
goto fail;
}
}
// Increase directory file size by cluster size
fileSize_ += 512UL*vol_->blocksPerCluster_;
return pc;
fail:
return 0;
}
//------------------------------------------------------------------------------
// cache a file's directory entry
// return pointer to cached entry or null for failure
dir_t* SdBaseFile::cacheDirEntry(uint8_t action) {
cache_t* pc;
pc = vol_->cacheFetch(dirBlock_, action);
if (!pc) {
DBG_FAIL_MACRO;
goto fail;
}
return pc->dir + dirIndex_;
fail:
return 0;
}
//------------------------------------------------------------------------------
/** Close a file and force cached data and directory information
* to be written to the storage device.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include no file is open or an I/O error.
*/
bool SdBaseFile::close() {
bool rtn = sync();
type_ = FAT_FILE_TYPE_CLOSED;
return rtn;
}
//------------------------------------------------------------------------------
/** Check for contiguous file and return its raw block range.
*
* \param[out] bgnBlock the first block address for the file.
* \param[out] endBlock the last block address for the file.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include file is not contiguous, file has zero length
* or an I/O error occurred.
*/
bool SdBaseFile::contiguousRange(uint32_t* bgnBlock, uint32_t* endBlock) {
// error if no blocks
if (firstCluster_ == 0) {
DBG_FAIL_MACRO;
goto fail;
}
for (uint32_t c = firstCluster_; ; c++) {
uint32_t next;
if (!vol_->fatGet(c, &next)) {
DBG_FAIL_MACRO;
goto fail;
}
// check for contiguous
if (next != (c + 1)) {
// error if not end of chain
if (!vol_->isEOC(next)) {
DBG_FAIL_MACRO;
goto fail;
}
*bgnBlock = vol_->clusterStartBlock(firstCluster_);
*endBlock = vol_->clusterStartBlock(c)
+ vol_->blocksPerCluster_ - 1;
return true;
}
}
fail:
return false;
}
//------------------------------------------------------------------------------
/** Create and open a new contiguous file of a specified size.
*
* \note This function only supports short DOS 8.3 names.
* See open() for more information.
*
* \param[in] dirFile The directory where the file will be created.
* \param[in] path A path with a valid DOS 8.3 file name.
* \param[in] size The desired file size.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include \a path contains
* an invalid DOS 8.3 file name, the FAT volume has not been initialized,
* a file is already open, the file already exists, the root
* directory is full or an I/O error.
*
*/
bool SdBaseFile::createContiguous(SdBaseFile* dirFile,
const char* path, uint32_t size) {
uint32_t count;
// don't allow zero length file
if (size == 0) {
DBG_FAIL_MACRO;
goto fail;
}
if (!open(dirFile, path, O_CREAT | O_EXCL | O_RDWR)) {
DBG_FAIL_MACRO;
goto fail;
}
// calculate number of clusters needed
count = ((size - 1) >> (vol_->clusterSizeShift_ + 9)) + 1;
// allocate clusters
if (!vol_->allocContiguous(count, &firstCluster_)) {
remove();
DBG_FAIL_MACRO;
goto fail;
}
fileSize_ = size;
// insure sync() will update dir entry
flags_ |= F_FILE_DIR_DIRTY;
return sync();
fail:
return false;
}
//------------------------------------------------------------------------------
/** Return a file's directory entry.
*
* \param[out] dir Location for return of the file's directory entry.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdBaseFile::dirEntry(dir_t* dir) {
dir_t* p;
// make sure fields on SD are correct
if (!sync()) {
DBG_FAIL_MACRO;
goto fail;
}
// read entry
p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
if (!p) {
DBG_FAIL_MACRO;
goto fail;
}
// copy to caller's struct
memcpy(dir, p, sizeof(dir_t));
return true;
fail:
return false;
}
//------------------------------------------------------------------------------
/** Format the name field of \a dir into the 13 byte array
* \a name in standard 8.3 short name format.
*
* \param[in] dir The directory structure containing the name.
* \param[out] name A 13 byte char array for the formatted name.
*/
void SdBaseFile::dirName(const dir_t& dir, char* name) {
uint8_t j = 0;
for (uint8_t i = 0; i < 11; i++) {
if (dir.name[i] == ' ') continue;
if (i == 8) name[j++] = '.';
name[j++] = dir.name[i];
}
name[j] = 0;
}
//------------------------------------------------------------------------------
/** Test for the existence of a file in a directory
*
* \param[in] name Name of the file to be tested for.
*
* The calling instance must be an open directory file.
*
* dirFile.exists("TOFIND.TXT") searches for "TOFIND.TXT" in the directory
* dirFile.
*
* \return true if the file exists else false.
*/
bool SdBaseFile::exists(const char* name) {
SdBaseFile file;
return file.open(this, name, O_READ);
}
//------------------------------------------------------------------------------
/**
* Get a string from a file.
*
* fgets() reads bytes from a file into the array pointed to by \a str, until
* \a num - 1 bytes are read, or a delimiter is read and transferred to \a str,
* or end-of-file is encountered. The string is then terminated
* with a null byte.
*
* fgets() deletes CR, '\\r', from the string. This insures only a '\\n'
* terminates the string for Windows text files which use CRLF for newline.
*
* \param[out] str Pointer to the array where the string is stored.
* \param[in] num Maximum number of characters to be read
* (including the final null byte). Usually the length
* of the array \a str is used.
* \param[in] delim Optional set of delimiters. The default is "\n".
*
* \return For success fgets() returns the length of the string in \a str.
* If no data is read, fgets() returns zero for EOF or -1 if an error occurred.
**/
int16_t SdBaseFile::fgets(char* str, int16_t num, char* delim) {
char ch;
int16_t n = 0;
int16_t r = -1;
while ((n + 1) < num && (r = read(&ch, 1)) == 1) {
// delete CR
if (ch == '\r') continue;
str[n++] = ch;
if (!delim) {
if (ch == '\n') break;
} else {
if (strchr(delim, ch)) break;
}
}
if (r < 0) {
// read error
return -1;
}
str[n] = '\0';
return n;
}
//------------------------------------------------------------------------------
/** Get a file's name
*
* \param[out] name An array of 13 characters for the file's name.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdBaseFile::getFilename(char* name) {
dir_t* p;
if (!isOpen()) {
DBG_FAIL_MACRO;
goto fail;
}
if (isRoot()) {
name[0] = '/';
name[1] = '\0';
return true;
}
// cache entry
p = cacheDirEntry(SdVolume::CACHE_FOR_READ);
if (!p) {
DBG_FAIL_MACRO;
goto fail;
}
// format name
dirName(*p, name);
return true;
fail:
return false;
}
//------------------------------------------------------------------------------
void SdBaseFile::getpos(FatPos_t* pos) {
pos->position = curPosition_;
pos->cluster = curCluster_;
}
//------------------------------------------------------------------------------
/** List directory contents to stdOut.
*
* \param[in] flags The inclusive OR of
*
* LS_DATE - %Print file modification date
*
* LS_SIZE - %Print file size.
*
* LS_R - Recursive list of subdirectories.
*/
void SdBaseFile::ls(uint8_t flags) {
ls(flags, 0);
}
uint8_t SdBaseFile::lsRecursive(SdBaseFile *parent, uint8_t level, char *findFilename, SdBaseFile *pParentFound, bool isJson)
{
dir_t *p = NULL;
//uint8_t cnt=0;
//char *oldpathend = pathend;
bool firstFile = true;
parent->rewind();
while ((p = parent->getLongFilename(p, tempLongFilename, 0, NULL)))
{
HAL::pingWatchdog();
if (! (DIR_IS_FILE(p) || DIR_IS_SUBDIR(p))) continue;
if (strcmp(tempLongFilename, "..") == 0) continue;
if (tempLongFilename[0] == '.') continue; // MAC CRAP
if (DIR_IS_SUBDIR(p)) {
if (level >= SD_MAX_FOLDER_DEPTH) continue; // can't go deeper
if (level < SD_MAX_FOLDER_DEPTH && findFilename == NULL) {
if (level && !isJson) {
Com::print(fullName);
Com::printF(Com::tSlash);
}
#if JSON_OUTPUT
if (isJson) {
if (!firstFile) Com::print(',');
Com::print('"');Com::print('*');
SDCard::printEscapeChars(tempLongFilename);
Com::print('"');
firstFile = false;
} else {
Com::print(tempLongFilename);
Com::printFLN(Com::tSlash); // End with / to mark it as directory entry, so we can see empty directories.
}
#else
Com::print(tempLongFilename);
Com::printFLN(Com::tSlash); // End with / to mark it as directory entry, so we can see empty directories.
#endif
}
SdBaseFile next;
char *tmp;
if(level) strcat(fullName, "/");
strcat(fullName, tempLongFilename);
uint16_t index = (parent->curPosition()-31) >> 5;
if(!isJson && next.open(parent, index, O_READ))
{
if (next.lsRecursive(&next,level+1, findFilename, pParentFound,false))
return true;
}
parent->seekSet(32 * (index + 1));
if ((tmp = strrchr(fullName, '/'))!= NULL)
*tmp = 0;
else
*fullName = 0;
}
else
{
if (findFilename != NULL)
{
int8_t cFullname;
cFullname = strlen(fullName);
if (RFstrnicmp(fullName, findFilename, cFullname) == 0)
{
if (cFullname > 0)
cFullname++;
if (RFstricmp(tempLongFilename, findFilename+cFullname) == 0)
{
if (pParentFound != NULL)
*pParentFound = *parent;
return true;
}
}
}
else
{
if(level && !isJson)
{
Com::print(fullName);
Com::printF(Com::tSlash);
}
#if JSON_OUTPUT
if (isJson) {
if (!firstFile) Com::printF(Com::tComma);
Com::print('"');
SDCard::printEscapeChars(tempLongFilename);
Com::print('"');
firstFile = false;
} else
#endif
{
Com::print(tempLongFilename);
#if SD_EXTENDED_DIR
Com::printF(Com::tSpace, (long) p->fileSize);
#endif
Com::println();
}
}
}
}
return false;
}
//------------------------------------------------------------------------------
/** List directory contents.
*
* \param[in] pr Print stream for list.
*
* \param[in] flags The inclusive OR of
*
* LS_DATE - %Print file modification date
*
* LS_SIZE - %Print file size.
*
* LS_R - Recursive list of subdirectories.
*
* \param[in] indent Amount of space before file name. Used for recursive
* list to indicate subdirectory level.
*/
void SdBaseFile::ls(uint8_t flags, uint8_t indent) {
SdBaseFile parent;
rewind();
*fullName = 0;
pathend = fullName;
parent = *this;
lsRecursive(&parent, 0, NULL, NULL, false);
}
#if JSON_OUTPUT
void SdBaseFile::lsJSON() {
SdBaseFile parent;
rewind();
*fullName = 0;
parent = *this;
lsRecursive(&parent, 0, NULL, NULL, true);
}
#endif
//------------------------------------------------------------------------------
// saves 32 bytes on stack for ls recursion
// return 0 - EOF, 1 - normal file, or 2 - directory
int8_t SdBaseFile::lsPrintNext(uint8_t flags, uint8_t indent) {
dir_t dir;
//uint8_t w = 0;
while (1) {
if (read(&dir, sizeof(dir)) != sizeof(dir)) return 0;
if (dir.name[0] == DIR_NAME_FREE) return 0;
// skip deleted entry and entries for . and ..
if (dir.name[0] != DIR_NAME_DELETED && dir.name[0] != '.'
&& DIR_IS_FILE_OR_SUBDIR(&dir)) break;
}
// indent for dir level
for (uint8_t i = 0; i < indent; i++) Com::print(' ');
printDirName(dir, flags & (LS_DATE | LS_SIZE) ? 14 : 0, true);
// print modify date/time if requested
if (flags & LS_DATE) {
Com::print(' ');
printFatDate(dir.lastWriteDate);
Com::print(' ');
printFatTime(dir.lastWriteTime);
}
// print size if requested
if (!DIR_IS_SUBDIR(&dir) && (flags & LS_SIZE)) {
Com::print(' ');
Com::print(dir.fileSize);
}
Com::println();
return DIR_IS_FILE(&dir) ? 1 : 2;
}
//------------------------------------------------------------------------------
// format directory name field from a 8.3 name string
FSTRINGVALUE(illegalFileChars,"|<>^+=?/[];,*\"\\")
bool SdBaseFile::make83Name(const char* str, uint8_t* name, const char** ptr) {
uint8_t c;
uint8_t n = 7; // max index for part before dot
uint8_t i = 0;
// blank fill name and extension
while (i < 11) name[i++] = ' ';
i = 0;
while (*str != '\0' && *str != '/') {
c = *str++;
if (c == '.') {
if (n == 10) {
DBG_FAIL_MACRO;
goto fail; // only one dot allowed
}
n = 10; // max index for full 8.3 name
i = 8; // place for extension
} else {
// illegal FAT characters
#define FLASH_ILLEGAL_CHARS
#ifdef FLASH_ILLEGAL_CHARS
// store chars in flash
FSTRINGPARAM(p);
p = illegalFileChars;
uint8_t b;
while ((b = HAL::readFlashByte(p++))) {
if (b == c) {
DBG_FAIL_MACRO;
goto fail;
}
}
#else // FLASH_ILLEGAL_CHARS
// store chars in RAM
if (strchr("|<>^+=?/[];,*\"\\", c)) {
DBG_FAIL_MACRO;
goto fail;
}
#endif // FLASH_ILLEGAL_CHARS
// check size and only allow ASCII printable characters
if (i > n || c < 0X20 || c > 0X7E) {
c = '_';
}
// only upper case allowed in 8.3 names - convert lower to upper
name[i++] = c < 'a' || c > 'z' ? c : c + ('A' - 'a');
}
}
*ptr = str;
// must have a file name, extension is optional
return name[0] != ' ';
fail:
return false;
}
//------------------------------------------------------------------------------
/** Make a new directory.
*
* \param[in] parent An open SdFat instance for the directory that will contain
* the new directory.
*
* \param[in] path A path with a valid 8.3 DOS name for the new directory.
*
* \param[in] pFlag Create missing parent directories if true.
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
* Reasons for failure include this file is already open, \a parent is not a
* directory, \a path is invalid or already exists in \a parent.
*/
bool SdBaseFile::mkdir(SdBaseFile* parent, const char* path, bool pFlag) {
uint8_t dname[LONG_FILENAME_LENGTH+1];
SdBaseFile newParent;
if (openParentReturnFile(parent, path, dname, &newParent, pFlag))
{
return mkdir(&newParent, dname);
}
return false;
}
//------------------------------------------------------------------------------
bool SdBaseFile::mkdir(SdBaseFile* parent, const uint8_t *dname) {
dir_t d;
if (!parent->isDir()) {
DBG_FAIL_MACRO;
return false;
}
// create a normal file
if (!open(parent, dname, O_CREAT | O_EXCL | O_RDWR, true)) {
DBG_FAIL_MACRO;
return false;
}
// make entry for '.'
memset(&d, 0, sizeof(d));
d.creationDate = FAT_DEFAULT_DATE;
d.creationTime = FAT_DEFAULT_TIME;
d.lastAccessDate = d.creationDate;
d.lastWriteDate = d.creationDate;
d.lastWriteTime = d.creationTime;
d.name[0] = '.';
d.attributes = DIR_ATT_DIRECTORY;
for (uint8_t i = 1; i < 11; i++) d.name[i] = ' ';
if (write(&d, sizeof(dir_t)) < 0)
return false;
sync();
// make entry for '..'
d.name[1] = '.';
if (parent->isRoot()) {
d.firstClusterLow = 0;
d.firstClusterHigh = 0;
} else {
d.firstClusterLow = parent->firstCluster_ & 0XFFFF;
d.firstClusterHigh = parent->firstCluster_ >> 16;
}
if (write(&d, sizeof(dir_t)) < 0)
return false;
sync();
memset(&d, 0, sizeof(dir_t));
if (write(&d, sizeof(dir_t)) < 0)
return false;
sync();
// fileSize_ = 0;
type_ = FAT_FILE_TYPE_SUBDIR;
flags_ |= F_FILE_DIR_DIRTY;
return true;
}
//------------------------------------------------------------------------------
/** Open a file in the current working directory.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of open flags. see SdBaseFile::open(SdBaseFile*, const char*, uint8_t).
*
* \return The value one, true, is returned for success and
* the value zero, false, is returned for failure.
*/
bool SdBaseFile::open(const char* path, uint8_t oflag) {
return open(cwd_, path, oflag);
}
//------------------------------------------------------------------------------
/** Open a file or directory by name.
*
* \param[in] dirFile An open SdFat instance for the directory containing the
* file to be opened.
*
* \param[in] path A path with a valid 8.3 DOS name for a file to be opened.
*
* \param[in] oflag Values for \a oflag are constructed by a bitwise-inclusive
* OR of flags from the following list
*
* O_READ - Open for reading.
*
* O_RDONLY - Same as O_READ.
*
* O_WRITE - Open for writing.
*
* O_WRONLY - Same as O_WRITE.
*
* O_RDWR - Open for reading and writing.
*
* O_APPEND - If set, the file offset shall be set to the end of the
* file prior to each write.
*
* O_AT_END - Set the initial position at the end of the file.
*
* O_CREAT - If the file exists, this flag has no effect except as noted
* under O_EXCL below. Otherwise, the file shall be created