正在阅读C语言中的二进制文件(以块为单位)

djmepvbi  于 2022-12-02  发布在  其他
关注(0)|答案(2)|浏览(184)

我不擅长C语言,我想做一些简单的事情。我想打开一个二进制文件,读取1024字节的数据块并转储到一个缓冲区,处理缓冲区,读取另外1024字节的数据,并一直这样做,直到EOF。我知道我想如何/做缓冲区,但它的循环部分和文件I/O我一直卡住。
伪代码:

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
}
whhtz7ly

whhtz7ly1#

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
  }
}
k4emjkb1

k4emjkb12#

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

相关问题