我一直在努力用fread隨機字符。即使我添加字符串字符'\ 0'的結尾,有時在字符串的末尾會有一個隨機字符。FREAD填充串在C
這是我的代碼。
#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;
}
我也試着*的ACK [LEN-1] = '\ 0' 但程序崩潰(沒有被從該點上印刷)
這裏有一個輸出例如:
的ack在get_acks:1,2,3,4 09:09▒
這裏是文件內容:
貓new_acks.txt: 1,2,3,4次
[請參閱爲什麼不投的malloc()'和家庭'C'的'返回值的討論。(http://stackoverflow.com/q/605845/2173917)。 –
'的ack [LEN-1] = '\ 0';' - >'(*的ack)LEN-1] = '\ 0';' –
@MichaelWalz謝謝。我在我的代碼中進行了測試。我沒有把它放在這裏來減少行數。 – lmbcerqueira