Problem reading/writting binary files.

This is a discussion on Problem reading/writting binary files. within the C Programming forums, part of the General Programming Boards category; Hello, I've a small program with 4 functions. The first one reads data from a file and returns it as ...

  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
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,649
    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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,474
    also - do not use feof to control loop - read FAQ
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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, 01:11 AM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM
  5. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21