1

Below operation happens very frequently in our application ,whenever power failure happens dest.xml will be corrupted and i see only NULNULNULNULNUL when opened with Notepad++ . I have tried disabling cache and using combination of remove() and rename() for renaming src.xml.ignore to dest.xml . Still the same issue .Is there any way to resolve this problem during power failure

MemoryOutputStream file;
file << dir << '\\' << relPath << idToUse << ".xml.ignore";
CSString temp = file.AsString(); /* CSString is our  internalstring class it can be converted into const char* */
FileUtils::MakeDirsInFilePath( temp );

static const int NUM_RETRIES = 50;
static const int WAIT_AMT = 100;

int i;
for ( i = 0; i < NUM_RETRIES; ++i )
{
    FILE * fp = ::_fsopen( temp, "wb", _SH_DENYRW );
    if ( fp != 0 )
    {
        FileOutputStream fos( fp, true );
        fos << xml;
        if ( fos.Close() )
        {
            break;
        }

        FileUtils::Delete( temp );
    }
    Thread::SleepFor( WAIT_AMT );
}
if ( i == NUM_RETRIES )
{
    return false;
}

// move into place
//
file.Reset();
file << dir << '\\' << idToUse << ".xml";
CSString dest = file.AsString();

DWORD flags = MOVEFILE_COPY_ALLOWED|MOVEFILE_WRITE_THROUGH;
if (overwrite) flags |= MOVEFILE_REPLACE_EXISTING;
BOOL rc = ::MoveFileEx( src, dest, flags ); ///Dest file is getting corrupted
Gajukorse
  • 147
  • 2
  • 11
  • What behaviour are you wanting instead? – UKMonkey Mar 12 '18 at 13:25
  • 2
    Invest in a UPS. –  Mar 12 '18 at 13:25
  • Problem is our software is used by one of our customer who does not have UPS . We want either 0 or 1 like solution either MovefileEx should rename it without any issues or it should not happen (atomic) . – Gajukorse Mar 12 '18 at 13:53
  • I'm not sure what you expect us to help with, if the power goes off, everything stops running and the state is not saved and whatever was or was not written out the to hard drive is what is there (i.e. you can't `try`/`catch` a power loss). – crashmstr Mar 12 '18 at 14:02
  • You would need a [journaling file system](https://en.wikipedia.org/wiki/Journaling_file_system), but securing the power supply would be much easier. – Bo Persson Mar 12 '18 at 14:11
  • see also https://stackoverflow.com/questions/6525943/cause-of-corrupted-file-contents – Vladimir Ulchenko Jan 23 '19 at 13:07

1 Answers1

-2

You need to use synchronous IO, which means you're going to have to use the Windows API instead of FILE and fopen.

I haven't done Windows programming n years, but a quick Google search suggests you'll want to use CreateFile (I'm guessing the FILE_FLAG_NO_BUFFERING and FILE_FLAG_OVERLAPPED flags, but that's going of ctrl+f). Once you have the file handle, use WriteFile

Stephen Newell
  • 7,330
  • 1
  • 24
  • 28