Thread: Reading files - Buffer size

  1. #1
    Registered User (TNT)'s Avatar
    Join Date
    Aug 2001

    Reading files - Buffer size


    I am having problems reading a file into packet sized buffers.

    Each packet is 1024 bytes in size, and is being sent through a socket.

    Below, rep = number of packets, dwSize is the acutal size in bytes of the file.

    char szBuff[1024];
        rep = dwSize / 1024;
    // Small Packet (File Size < 1024)
    	if(rep <=0)
    		fread(szBuff, 1, dwSize, pFile);
    		send(theSocket, szBuff, dwSize, 0);
    // Larger Packets (File Size Bigger than 1024)
    	for(int i = 0; i < rep; i++)
    		fread(szBuff, 1, dwSize / 1024 * i, pFile);
    		send(theSocket, szBuff, 114, 0);
    As you can imagine the small packets work fine, as it is only a max of 1 packet big, which means i can read the actual file size stright into the packet buffer.

    However the larger packets im having problems with, say i have a 3000 byte file, there will be 2.92 packets to send.

    Now the problem is that im not sure how i can set fread() to read in the full packet size if its (in this case) 2 times, then the final time only read in the remaining .92 section of the full packet.

    I have tried doing it 3 times complete 1024 packets then null terminating the string but it just fills it with random memory characters and crap. The sizeof and strlen functions on the buffer dont help me much either as strlen says its 4 characters big possible becasue the file is encrypted.

    Any ideas on how i can make a packet reader loop cycle that works on files over 1024 bytes? Baring in mind i have the Packet number (i) full file size (dwSize) and total number of packets (rep).

    Thanks alot
    You Can Stop Me, But You Cant Stop Us All

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    fread() returns the number of bytes read, so you really don't need to worry about how big the file is, or how many buffers it takes
    while ( (n=fread(szBuff, 1, sizeof szBuff, pFile)) != 0 ) {
      send(theSocket, szBuff, n, 0);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  2. Getting the size of the client recv buffer
    By Niara in forum Networking/Device Communication
    Replies: 6
    Last Post: 10-27-2006, 11:46 AM
  3. error: identifier "byte" is undefined.
    By Hulag in forum C++ Programming
    Replies: 4
    Last Post: 12-10-2003, 05:46 PM
  4. Reading files in a directory
    By roktsyntst in forum Windows Programming
    Replies: 5
    Last Post: 02-07-2003, 10:04 AM
  5. problem reading files in C
    By angelfly in forum C Programming
    Replies: 9
    Last Post: 10-10-2001, 11:58 AM