我正在嘗試寫一個bittorrent客戶端。爲了解析文件等我需要讀取一個torrent文件到內存中。我注意到fread沒有將整個文件讀入我的緩衝區。經過進一步調查,似乎只要在文件中遇到下面顯示的符號,fread就會停止讀取文件。在FILE *指針上調用feof函數返回16,指示已到達文件末尾。無論符號放在哪裏,都會發生這種情況。有人可以解釋爲什麼會發生這種情況以及可能有效的解決方案。導致fread突然結束的右箭頭符號?
符號概述如下:
這裏是做讀操作的代碼:
char *read_file(const char *file, long long *len){
struct stat st;
char *ret = NULL;
FILE *fp;
//store the size/length of the file
if(stat(file, &st)){
return ret;
}
*len = st.st_size;
//open a stream to the specified file
fp = fopen(file, "r");
if(!fp){
return ret;
}
//allocate space in the buffer for the file
ret = (char*)malloc(*len);
if(!ret){
return NULL;
}
//Break down the call to fread into smaller chunks
//to account for a known bug which causes fread to
//behave strangely with large files
//Read the file into the buffer
//fread(ret, 1, *len, fp);
if(*len > 10000){
char *retTemp = NULL;
retTemp = ret;
int remaining = *len;
int read = 0, error = 0;
while(remaining > 1000){
read = fread(retTemp, 1, 1000, fp);
if(read < 1000){
error = feof(fp);
if(error != 0){
printf("Error: %d\n", error);
}
}
retTemp += 1000;
remaining -= 1000;
}
fread(retTemp, 1, remaining, fp);
} else {
fread(ret, 1, *len, fp);
}
//cleanup by closing the file stream
fclose(fp);
return ret;
}
感謝您的時間:)
那個符號的整數是多少? – chris 2012-07-18 17:55:57
當讀取多個字節時,其中一個是空字節? – 2012-07-18 17:55:58
你能發佈實際的代碼嗎? – YePhIcK 2012-07-18 18:02:49