簡體   English   中英

讀取 C 中的二進制文件(分塊)

[英]Reading binary file in C (in chunks)

我不擅長 C,我正在嘗試做一些簡單的事情。 我想打開一個二進制文件,讀取 1024 字節的數據塊並轉儲到緩沖區中,處理緩沖區,讀取另外 1024 字節的數據並繼續這樣做直到 EOF。 我知道我想用緩沖區做什么/做什么,但它是循環部分,文件 I/OI 一直卡在上面。

偽代碼:

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()返回讀取的字節數。 你可以循環直到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;
}

添加了編輯代碼

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM