Thread: buffer contents swapping

  1. #1
    Registered User daluu's Avatar
    Join Date
    Dec 2002
    Posts
    42

    buffer contents swapping

    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;
    }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    This is not C...
    Code:
    void swaphalves(FILE* afile, long& byte, char* buffer){
    Are you compiling with a C++ compiler or something?
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User daluu's Avatar
    Join Date
    Dec 2002
    Posts
    42
    yes, it's a mix of C & C++, technically. I know, I know that's bad...

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    "A mix of C & C++" makes it C++. As such, it should be posted on that forum.

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Given a suitable buffer
    Code:
    fread( &buff[size/2], size/2, 1, fp );
    fread( buff[0], size/2, 1, fp );
    fwrite( buff, size, 1, out );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User daluu's Avatar
    Join Date
    Dec 2002
    Posts
    42

    update on the program - swaphalves() problem

    I looked over my code and refined it as best I could. I pinpointed the problem to swaphalves(). my buffer read & write functions are ok.

    for an input file content of: todo
    (which is 4 bytes)

    if i run read buffer function and swaphalves but don't call a buffer write, I get : tooto

    when the result should be: toot
    because a final write buffer should produce: odot
    if I call write buffer now, i get: odoto

    I can't make out where the extra character at the end comes from. Can you help me trace its source?

    Here's the refined swaphalves code:
    Code:
    void swaphalves(char* buffer){
    
    	int nread = (int) readto;  //counter to check EOF
    	int fend = (int) fsize;	   //indicates EOF
    	int byte;				   //tmp var to stor a byte
    	long back = -1L;		   //var for seeking back 1 byte
    	int revpos = (int) readto; //counter for reversing buffer contents
    	revpos--;					//workaround as ((int) readto) - 1 gave bad result
    	
    	while(((byte = fgetc(dfile)) != EOF) && (nread < fend)){
    		
    		//loop to swap a byte from current file pos with current buffer pos
    
    		//put back last byte in buffer to file, seek back 1
    		fseek(dfile,back,SEEK_CUR);
    		fputc(buffer[revpos],dfile);
    		//file ptr will auto mov to original pos after call to fputc
    		
    		//put latest byte read from file to end of buffer & decrement buffer position
    		buffer[revpos--] = (char) byte;
    		
    		//get next byte in file in next while loop
    		nread++; //increment # bytes read indicator
    	}
    
    	return;
    }
    last, how might I go about moving a post to another forum say C++ without double posting?

  7. #7
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Posting to another fourm, the mods will do that for you. As to your code. Please post your refactored program so we can see it in full.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  8. #8
    Registered User daluu's Avatar
    Join Date
    Dec 2002
    Posts
    42
    pardon the possibly messy code, it's in testing phase:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    /*fncs*/
    long FileSize (FILE *stream);
    void readfirst(char* buffer);
    void writefirst(char* buffer);
    void swaphalves(char* buffer);
    
    //Declare global variables
    //Global variables used to avoid passing variables into functions
    FILE *dfile; //file handle for database file
    long fsize; //var used to calculate filesize
    long readto; //var used to read/write half of file
    
    int main(int argc,char *argv[])
    {	
    	//1 - check input
    	if (argc<2)
    	{
    		puts("No input file specified. Please type command again with filename.\n");
    		return 0;//Self explanatory
    	}
    	
    	//2 - Open input file
    	dfile = fopen(argv[1], "rb+");
    	//Abort program & display error if file open fails
    	if(dfile==NULL)
    	{
    		printf("Bad filename or file does not exist.\n");
    		return 1;
    	}
    
    	//3 - Get file size
    	fsize = FileSize(dfile);
    	readto = fsize/2;
    	//not dealing with ODD file size cases at present
    	
    	char *buffer;
    	buffer = (char*) malloc( sizeof(char)*readto );
    	
    	//4 - read in half of file contents
    	readfirst(buffer);
    
    	//5 - swap contents in buffer w/ content in 2nd half of file
    	swaphalves(buffer);
    
    	//6 - write back swapped half of file to 1st half of file
    	//writefirst(buffer);	
    
    	//7 - Notify operation complete
    	puts("Half file swap operation completed.\n");
    	
    	//8 - Exit program
    	free(buffer);
    	fclose(dfile);
    	return 0;
    }
    
    long FileSize (FILE *stream)
    {
    	long length;//temp variable
    	fseek (stream, 0L, SEEK_END);//seek to EOF
    	length = ftell(stream);//store EOF byte position which is filesize
    	//reset file for future reading by seeking to origin
    	fseek (stream, 0L, SEEK_SET);
    	return length;//return filesize
    }
    
    void swaphalves(char* buffer){
    
    	int nread = (int) readto;  //counter to check EOF
    	int fend = (int) fsize;	   //indicates EOF
    	int byte;		   //tmp var to stor a byte
    	long back = -1L;	   //var for seeking back 1 byte
    	int revpos = (int) readto; //counter for reversing buffer contents
    	revpos--;		   //workaround as ((int) readto) - 1 gave bad result
    	
    	while(((byte = fgetc(dfile)) != EOF) && (nread < fend)){
    		
    		//loop to swap a byte from current file pos with current buffer pos
    
    		//put back last byte in buffer to file, seek back 1
    		fseek(dfile,back,SEEK_CUR);
    		fputc(buffer[revpos],dfile);
    		//file ptr will auto mov to original pos after call to fputc
    		
    		//put latest byte read from file to end of buffer & decrement buffer position
    		buffer[revpos--] = (char) byte;
    		
    		//get next byte in file in next while loop
    		nread++; //increment # bytes read indicator
    	}
    	return;
    }
    
    void writefirst(char* buffer){
    	fseek (dfile, 0L, SEEK_SET);
    	fwrite(buffer,readto,1,dfile);
    	return;
    }
    
    void readfirst(char* buffer){
    	fread(buffer,readto,1,dfile);
    	return;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. buffer has extra contents in gtk+ 2.0
    By MK27 in forum Linux Programming
    Replies: 5
    Last Post: 08-04-2008, 11:57 AM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  4. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM
  5. Validating the contents of a char buffer
    By mattz in forum C Programming
    Replies: 3
    Last Post: 12-09-2001, 06:21 PM