Go to English page

ViaThinkSoft CodeLib

Dieser Artikel befindet sich in der Kategorie:
CodeLibProgrammierhilfenC / 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 Mitbegründer