52 lines
1.5 KiB
C
52 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
|
|
int main() {
|
|
FILE *fp; // file pointer
|
|
float *data; // data pointer (array of floats)
|
|
int i, file_size, arr_size;
|
|
char filename[2049];
|
|
|
|
printf("Enter filename to read: ");
|
|
scanf("%2048s", filename);
|
|
|
|
fp = fopen(filename, "rb");
|
|
if (fp == NULL) {
|
|
printf("Failed to open file\n");
|
|
return 1;
|
|
}
|
|
|
|
// get file size (technically isn't the best way because SEEK_END is undefined behaviour:
|
|
//
|
|
// "Library implementations are allowed to not meaningfully support SEEK_END
|
|
// (therefore, code using it has no real standard portability)."
|
|
// ~ https://cplusplus.com/reference/cstdio/fseek/
|
|
//
|
|
// " Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END),
|
|
// has undefined behavior for a binary stream (because of possible trailing null characters) or
|
|
// for any stream with state-dependent encoding that does not assuredly end in the initial shift
|
|
// state. "
|
|
// ~ https://port70.net/~nsz/c/c11/n1570.html#note268
|
|
//
|
|
// it is also limited to 2GB files as it returns a signed integer
|
|
// better to use something like this probably:
|
|
// https://stackoverflow.com/a/238609
|
|
//
|
|
// but louise uses fseek so i will too
|
|
fseek(fp, 0, SEEK_END);
|
|
file_size = ftell(fp);
|
|
arr_size = file_size/sizeof(float);
|
|
rewind(fp);
|
|
|
|
// allocate memory and read data
|
|
data = malloc(file_size);
|
|
fread(data, sizeof(float), arr_size, fp);
|
|
|
|
for (i = 0; i < arr_size; i++) {
|
|
printf("%d %0.3f\n", i, data[i]);
|
|
}
|
|
|
|
free(data);
|
|
}
|