Click here to Skip to main content
13,048,584 members (79,661 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am trying to copy a text file to a buffer in order to send it over the socket. As soon as the text file does not have any newlines (or \n), the file is successfully copied into buffer. But, whenever there are multiple lines in a text file, I get an error, "Unable to copy file into buffer".

Below is the code snippet:
//=====================Sending a File at Socket=========================
   FILE *fp = fopen("File.txt", "r+");
   char file_buffer[1000];
   fseek(fp, 0, SEEK_SET);
   int bytes_read=0;
   if((bytes_read=fread(file_buffer, 1, file_size, fp))<=0)
       MessageBox( NULL,
               "Unable to copy file into buffer",
               MB_ICONEXCLAMATION |
     MessageBox( NULL,
            "File copied in Buffer",

NOTE: The code works perfectly fine if the text file contains no new lines.
Posted 7-May-13 19:11pm
Updated 7-May-13 20:52pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

This code is NOT fine: file_size is not initialized and you should never call fread before being sure that the count (in your case file_size itself) argument is less than (or equal to) the size of the provided buffer.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

opening the file in binary mode solved the problem :)
fopen must be as follows:
FILE *fp = fopen("File.txt", "r+b");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 8 May 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100