作者peefly (Peefly)
看板C_and_CPP
標題[問題] fread讀檔時file indicator不依序遞增?
時間Sat Mar 21 04:12:32 2009
我寫了一個簡易複製檔案的小程式,程式碼如下
--
#include <stdio.h>
typedef char byte;
int main()
{
FILE *f,*tf;
byte t;
char path[30],newpath[50];
do{
printf("Filepath=");
scanf("%s",path);
f=fopen(path,"r"); //開檔
if(f==NULL)printf("File not exist!\n");//判斷開檔是否成功
}while(f==NULL);
sprintf(newpath,"new-%s",path);//組合新檔名
tf=fopen(newpath,"w");
while( 1 )
{
if( fread(&t,sizeof(byte),1,f) ==0 )break;//讀檔
printf("ftell=0x%x t=0x%x\n",ftell(f),t);
fwrite(&t,sizeof(byte),1,tf);//寫檔
}
fclose(f);
fclose(tf);
}
--
在處理小檔案時都能順利成功
但是只要檔案稍大一點,如下面網址的圖
http://www.dowwallpaper.com/wallpaper/placennature/forest/forest2.jpg
就會發生複製不完整的情況
甚至只有複製到前不到10個bytes
我用ftell查file indicator時,發現他有時並不是每次都會+1
甚至會亂跳,如上面那張圖會從0x3e1e跳到0x4000
0x496f跳到0x4971之類的
所以無法讀取到每個byte、複製完整
請問到底是什麼原因,會造成file indicator亂跳呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.118.234.64
1F:→ peefly:疑@@ 我把相同的程式碼丟到Linux中執行竟然都能複製成功 03/21 04:23
2F:推 littleshan: Windows 要用 binary mode 開檔 03/21 09:12
3F:→ peefly:哦 原來要特別加b .. 感謝樓上! 03/21 12:35