Gehe zu deutscher Webseite

ViaThinkSoft CodeLib

This article is in:
CodeLibProgramming aidsC / C++


int binary_replace_file(const char* filename, unsigned int search, unsigned int replace) {
        unsigned int srecord = 0;
        int found = 0;

        FILE* fptr = fopen(filename, "rb+");
        if (fptr == NULL) return -1;

        while ((fread(&srecord, sizeof(srecord), 1, fptr) == 1))
        {
                if (srecord == search) {
                        srecord = replace;
                        fseek(fptr, -1*(long)sizeof(srecord), SEEK_CUR);
                        fwrite(&srecord, (int)sizeof(srecord), 1, fptr);
                        fseek(fptr, 0, SEEK_CUR); // important!
                        found++;
                }
                else {
                        fseek(fptr, -1*(long)(sizeof(srecord) - 1), SEEK_CUR);
                }
        }
        fclose(fptr);

        return found;
}
Daniel Marschall
ViaThinkSoft Co-Founder

Feedback? Problems? Please drop us a message!

Your name (optional):

E-mail address (optional):

Message: