Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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:
C#
//=====================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",
               "Error!",
               MB_ICONEXCLAMATION |
               MB_OK);
      exit(1);
     }
     MessageBox( NULL,
             file_buffer,
            "File copied in Buffer",
            MB_ICONEXCLAMATION |
            MB_OK);


NOTE: The code works perfectly fine if the text file contains no new lines.
Posted
Updated 7-May-13 20:52pm
v2

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.
 
Share this answer
 
opening the file in binary mode solved the problem :)
fopen must be as follows:
FILE *fp = fopen("File.txt", "r+b");
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900