Click here to Skip to main content
11,581,130 members (66,400 online)
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 19:11pm
Edited 7-May-13 20: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 250
1 Frankie-C 185
2 Sergey Alexandrovich Kryukov 85
3 Dave Kreskowiak 83
4 F-ES Sitecore 80
0 OriginalGriff 1,183
1 Sergey Alexandrovich Kryukov 825
2 Abhinav S 597
3 F-ES Sitecore 500
4 Suvendu Shekhar Giri 433


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