I need another pair of eyes, etc. to review my code for logic errors.
Here's what the program should do:
1. read in half of input file to buffer
2. read last half BUT swap each byte read with last byte from buffer back into
file, decrementing buffer end position each time.
3. write back buffer contents to 1st half of file.
in other words, it should reverse the contents of the file. running the program
twice should give you back the original file. AND rules 1-3 must be followed.
Problem for me is my code works OK for 2 byte as this is what I get running
program twice.
as -> sa -> as
But for 4 bytes or more, error.
For 4 bytes, this is what happens to contents
todo -> .dot -> .od.
More bytes = messed up text
I can't seem to find the logic error in my code. Can you?
functions called in this order:
readfirst()
swaphalves() //error in here?
writefirst()
Here's what I have:
Code://global vars FILE *dfile; //file handle long fsize; //var used to calculate filesize long readto; //var used to read/write half of file long back = -1; //for seeking long forward = 1; //vars in main() long byte = 0; fsize = FileSize(dfile); readto = fsize/2; char *buffer; buffer = (char*) malloc( sizeof(char)*readto ); //this function seems to be the problem void swaphalves(FILE* afile, long& byte, char* buffer){ unsigned char chr; long revpos = byte-1; //counter for reversing buffer contents chr = fgetc(afile); byte++; while(byte < fsize){ //while(!feof(dfile)){ //put back last char in buffer to file, seek back 1 fseek (afile, back, SEEK_CUR); fputc(buffer[revpos],afile); //put latest char read from file to current buffer pos & decrement buffer pos buffer[revpos--] = chr; //seek forward 1 for get next char fseek (afile, forward, SEEK_CUR); chr = fgetc(afile); byte++; } //take care of last char //put back last char in buffer to file, seek back 1 fseek (afile, back, SEEK_CUR); fputc(buffer[revpos],afile); //put latest char read from file to current buffer pos buffer[revpos] = chr; //fseek (afile, forward, SEEK_CUR); //for debugging printf("Buffer: "); for(int i = 0; i < readto; i++) printf("%c",buffer[i]); return; } //function works ok in testing void readfirst(FILE* afile, long& byte, char* buffer){ buffer[byte] = fgetc(afile); byte++; while(byte < readto) buffer[byte++] = fgetc(afile); //for debugging printf("Buffer: "); for(int i = 0; i < readto; i++){ printf("%c",buffer[i]); } putchar('\n'); return; } //function should be ok i believe void writefirst(FILE* afile, const long& length, char* buffer){ fseek (afile, 0L, SEEK_SET); fwrite(buffer,sizeof(char),length,afile); return; }



LinkBack URL
About LinkBacks


