I've been struggling with fread. Even though I'm adding the end of string character '\0', sometimes there is a random character at the end of the string.
Here is my code.
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
uint8_t get_acks(char ** acks);
int main(){
...
char *acks = NULL;
uint8_t r = get_acks(&acks);
// test r ...
}
uint8_t get_acks(char ** acks){
FILE *fp;
fp = fopen(FILENAME, "r");
// test fp
fseek(fp, 0, SEEK_END);
long len = ftell(fp);
fseek(fp, 0, SEEK_SET);
*acks = malloc(sizeof(char)*(len+1));
fread(*acks, sizeof(char), len, fp);
acks[len-1] = '\0';
printf("acks in get_acks: %s", *acks);
return 0;
}
I've also tried *acks[len-1] = '\0' but the program crashes (nothing is printed from that point on)
Here you have an output example:
acks in get_acks: 1, 2, 3, 4 09:09▒
Here is the file content:
cat new_acks.txt: 1, 2, 3, 4