简体   繁体   中英

Reading binary file in C (in chunks)

I'm not good at C and I'm trying to do something simple. I want to open a binary file, read blocks of 1024 bytes of data and dump into a buffer, process the buffer, read another 1024 byes of data and keep doing this until EOF. I know how / what I want to do with the buffer, but it's the loop part and file I/OI keep getting stuck on.

PSEUDO code:

FILE *file;
unsigned char * buffer[1024];

fopen(myfile, "rb");

while (!EOF)
{
  fread(buffer, 1024);
  //do my processing with buffer;
  //read next 1024 bytes in file, etc.... until end
}

fread() returns the number of bytes read. You can loop until that's 0.

FILE *file = NULL;
unsigned char buffer[1024];  // array of bytes, not pointers-to-bytes
size_t bytesRead = 0;

file = fopen(myfile, "rb");   

if (file != NULL)    
{
  // read up to sizeof(buffer) bytes
  while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0)
  {
    // process bytesRead worth of data in buffer
  }
}
#include <stdio.h>
#include <unistd.h> // For system calls write, read e close
#include <fcntl.h>

#define BUFFER_SIZE 1024

int main(int argc, char* argv[]) {
    unsigned char buffer[BUFFER_SIZE] = {0};
    ssize_t byte = 0;
    
    int fd = open("example.txt", O_RDONLY);
    
    while ((byte = read(fd, buffer, sizeof(buffer))) != 0) {
        printf("%s", buffer);
        memset(buffer, 0, BUFFER_SIZE);
    }
    
    close(fd);
    
    return 0;
}

Edited code added

#include <stdio.h>
#include <unistd.h> // For system calls write, read e close
#include <fcntl.h>

#define BUFFER_SIZE 1024

int main(int argc, char* argv[]) {
    unsigned char buffer[BUFFER_SIZE] = {0};
    ssize_t byte = 0;
    
    // open file in read mode
    int fd = open("example.txt", O_RDONLY);
    
    // file opening failure
    if (fd == -1) {
        printf("Failed to open file\n");
        return -1;
    }
    
    // loop
    while (1) {
        // read buffer
        byte = read(fd, buffer, sizeof(buffer));
        // error
        if (byte == -1) {
            printf("Encountered an error\n");
            break;
        } else if (byte == 0) {
            // file end exit loop
            printf("File reading end\n");
            break;
        }
        
        // printf file data
        printf("%s", buffer);
        memset(buffer, 0, BUFFER_SIZE);
    
    }
    
    // Close file
    close(fd);
    
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM