Thread: Question in read file

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    1

    Question in read file

    I am a beginner in C and am having a problem when mapping documents into a file, because some lines contain null characters, how can I fix this?

    Code:
    void mapFilePositional(const char *breaker, int breakerPosition, document **documents, FILE **input){
    	char		  *buffer;
    	unsigned int  pivot 		= 0,
    				  lineSize 		= 0,
    				  breakerSize 	= strlen(breaker);
    	unsigned long position 		= 0;
    
    	buffer 	= (char*)malloc(BUFFER_SIZE * sizeof(char));
    	
    	while(fgets(buffer, BUFFER_SIZE, *input) != NULL){
    	
    		if(strncmp((buffer + breakerPosition - 1), breaker, breakerSize) == 0){
    			if((pivot % DOCUMENT_SIZE) == 0){
    				if(allocateDocument(documents, DOCUMENT_SIZE * ((pivot % DOCUMENT_SIZE) + 1)) == 0){
    					printf("Error: error to allocate struct.!\n"); 
    					abort();
    				}
    			}
    			
    			(*documents + pivot)->initialPosition 	= position;
    			(*documents + pivot)->size				= lineSize;
    			
    			position += lineSize;
    			lineSize = 0;
    			pivot++;
    		}
    		lineSize +=  strlen(buffer);
    	}
    
    	free(buffer);
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    If it contains \0 characters, then it really isn't a text file, and using fgets() will lead to loss of information.

    Use fread() if it is a binary file.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  2. Replies: 21
    Last Post: 06-16-2008, 02:44 PM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM