[英]How to read 16 bytes from a file at a time and store them into an array
[英]Read bytes from file and store in array - C
我正在嘗試使用fread從.raw文件讀取所有字節並將其存儲在數組中。 這是我的代碼:
//open up card file
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
printf("Unable to open/create file\n");
return 1;
}
//size of file
fseek(file, 0, SEEK_END);
int size = ftell(file);
fseek(file, 0, SEEK_SET);
//buffer array
int buffer[size];
fread(&buffer, 512, size/512, file);
return(0);
我想一次讀取512個字節,並且文件中的所有內容都讀取一次。 現在我的代碼給我Segmanetation Fault
,這為什么呢? 我想這與內存泄漏或類似的問題有關,但我無法弄清楚。 我還嘗試將文件file
的模式更改為w
但是所有文件內容都消失了。 我究竟做錯了什么?
因此,您的代碼存在一些問題:
size
和int buffer[size]
: size
是文件中的字節數,因此創建一個大小為size
的整數數組實際上將使用size * 4
個字節。 您在注釋中提到您的文件為14.3MB,因此buffer
陣列為57.2MB。 如果您實際上想讀取4個字節的整數,那么您需要相應地調整buffer
數組的大小(除以4並考慮余數-稍后再介紹)。 ulimit -s
以查看堆棧中的最大千字節數。 在我的機器,這是8 MB,並試圖fread
成一個更大的陣列導致段錯誤。 如果要將整個文件讀入內存,則需要使用堆( malloc
/ free
)。 size/512
:整數除法會丟棄余數,因此此計算是錯誤的。 buffer
的地址(您正在使用&buffer
),而是想要傳遞buffer
的第一個元素的地址,這可以方便地通過僅使用buffer
(或&buffer[0]
來完成,但是在現實中很少看到這一點)。 這是程序的“工作”版本:
#include <stdio.h>
#include <stdlib.h>
#define BYTES_PER_READ 512
int main(int argc, char *argv[])
{
long size;
size_t number_of_ints;
size_t number_of_elements;
size_t read;
int *buffer;
/* Open up card file */
FILE *file = fopen("card.raw", "r");
if (!file) {
fprintf(stderr, "Unable to open/create file\n");
return 1;
}
/* Size of file */
fseek(file, 0, SEEK_END);
size = ftell(file);
fseek(file, 0, SEEK_SET);
/* 'size' is the number of bytes, not the number of ints,
so we need to adjust accordingly */
number_of_ints = (size % sizeof(int) ? 1 : 0) + (size / sizeof(int));
/* We want to read 512 bytes at a time, and we need to know
how many we need to read to consume the whole file
(this is identical to the calculation above) */
number_of_elements = (size % BYTES_PER_READ ? 1 : 0) +
(size / BYTES_PER_READ);
if (!(buffer = malloc(number_of_ints * sizeof(int)))) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;
}
read = fread(buffer, BYTES_PER_READ, number_of_elements, file);
printf("I read %zu elements of size %d bytes (total bytes read: %zu)\n",
read, BYTES_PER_READ, read * BYTES_PER_READ);
free(buffer);
return 0;
}
如果您可以描述您打算對buffer
數組的內容做什么,那么有人可能會告訴您一種更好的解決方法(您現在正在閱讀的方式有點奇怪...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.