This repository has been archived on 2023-10-26. You can view files and clone it, but cannot push or open issues or pull requests.
VSMechatronics/C18/ex6.c

52 lines
1.5 KiB
C
Raw Normal View History

2023-10-07 14:16:39 +00:00
#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);
}