Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to 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:
//=====================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 7-May-13 20:11pm
Edited 7-May-13 21:52pm
v2
Rate this: bad
good
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.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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

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

  Print Answers RSS
0 OriginalGriff 304
1 Maciej Los 285
2 Sergey Alexandrovich Kryukov 255
3 Shweta N Mishra 216
4 PIEBALDconsult 174
0 OriginalGriff 7,660
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,760


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 8 May 2013
Copyright © CodeProject, 1999-2014
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