@@ -588,8 +588,8 @@ bool ExFatFile::truncate() {
588588 }
589589 }
590590 }
591+ m_validLength = m_curPosition > m_validLength ? m_validLength : m_curPosition;
591592 m_dataLength = m_curPosition;
592- m_validLength = m_curPosition;
593593 m_flags |= FILE_FLAG_DIR_DIRTY;
594594 return sync ();
595595
@@ -605,18 +605,25 @@ size_t ExFatFile::write(const void* buf, size_t nbyte) {
605605 uint16_t sectorOffset;
606606 uint32_t sector;
607607 uint32_t clusterOffset;
608-
609- // number of bytes left to write - must be before goto statements
608+ uint64_t toFill = 0 ;
610609 size_t toWrite = nbyte;
611610 size_t n;
611+
612612 // error if not an open file or is read-only
613613 if (!isWritable ()) {
614614 DBG_FAIL_MACRO;
615615 goto fail;
616616 }
617617 // seek to end of file if append flag
618618 if ((m_flags & FILE_FLAG_APPEND)) {
619- if (!seekSet (m_validLength)) {
619+ if (!seekSet (m_dataLength)) {
620+ DBG_FAIL_MACRO;
621+ goto fail;
622+ }
623+ }
624+ if (m_curPosition > m_validLength) {
625+ toFill = m_curPosition - m_validLength;
626+ if (!seekSet (m_validLength)) {
620627 DBG_FAIL_MACRO;
621628 goto fail;
622629 }
@@ -669,14 +676,10 @@ size_t ExFatFile::write(const void* buf, size_t nbyte) {
669676 sector = m_vol->clusterStartSector (m_curCluster) +
670677 (clusterOffset >> m_vol->bytesPerSectorShift ());
671678
672- if (sectorOffset != 0 || toWrite < m_vol->bytesPerSector ()) {
679+ if (sectorOffset != 0 || toWrite < m_vol->bytesPerSector () || toFill ) {
673680 // partial sector - must use cache
674681 // max space in sector
675682 n = m_vol->bytesPerSector () - sectorOffset;
676- // lesser of space and amount to write
677- if (n > toWrite) {
678- n = toWrite;
679- }
680683
681684 if (sectorOffset == 0 && m_curPosition >= m_validLength) {
682685 // start of new sector don't need to read into cache
@@ -691,7 +694,18 @@ size_t ExFatFile::write(const void* buf, size_t nbyte) {
691694 goto fail;
692695 }
693696 uint8_t * dst = cache + sectorOffset;
694- memcpy (dst, src, n);
697+
698+ if (toFill) {
699+ if (n > toFill) {
700+ n = toFill;
701+ }
702+ memset (dst, 0 , n);
703+ } else {
704+ if (n > toWrite) {
705+ n = toWrite;
706+ }
707+ memcpy (dst, src, n);
708+ }
695709 if (m_vol->bytesPerSector () == (n + sectorOffset)) {
696710 // Force write if sector is full - improves large writes.
697711 if (!m_vol->dataCacheSync ()) {
@@ -723,8 +737,12 @@ size_t ExFatFile::write(const void* buf, size_t nbyte) {
723737 }
724738 }
725739 m_curPosition += n;
726- src += n;
727- toWrite -= n;
740+ if (toFill) {
741+ toFill -= n;
742+ } else {
743+ src += n;
744+ toWrite -= n;
745+ }
728746 if (m_curPosition > m_validLength) {
729747 m_flags |= FILE_FLAG_DIR_DIRTY;
730748 m_validLength = m_curPosition;
0 commit comments