Thread: Problem reading/writting binary files.

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Problem reading/writting binary files.

    Hello,
    I've a small program with 4 functions.
    The first one reads data from a file and returns it as a string(text_from_file)
    Code:
    int read_file (char* file_to_open, char* text_from_file){
            FILE *fp;
    	char tmp_str[MAX_STR];
    if((fp = fopen(file_to_open, "r"))==NULL) {
        	printf("Cannot open file.\n");
        	exit(1);
      	} 
    	while (!feof(fp)){		
    		fgets(tmp_str,MEGABYTE,fp);
    		strcat(text_from_file,tmp_str);	
    		}
    	fclose(fp);
    }
    Then that string slightly modified and written into a file. When the which I open is a text file, it works well but if I'm opening binary files it doesn't read the whole file, it only reads and returns a smaller string.
    What I'm doing wrong? any help would be appreciated

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    If it's a binary file, use fread, and don't try to treat the data like a string, because it's not in that case.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    also - do not use feof to control loop - read FAQ
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Binary Files I/O (fread function)
    By g33koo in forum C Programming
    Replies: 21
    Last Post: 09-30-2008, 04:56 AM
  2. Problem compiling files that store functions
    By tiachopvutru in forum C++ Programming
    Replies: 10
    Last Post: 05-30-2008, 05:42 PM
  3. Help with binary files
    By tuxinator in forum C Programming
    Replies: 3
    Last Post: 12-01-2005, 02:11 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM