作者andice780101 (寶寶)
看板C_and_CPP
標題[問題] fread 與 fwrite 基本問題
時間Sun Dec 1 16:43:26 2013
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
想請教 size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
size 與 count 的參數差異
我測試一個讀檔程式, 大致是分為這兩種讀檔方式
fread ( in_buf, 1, 10, file );
fread ( in_buf, 2, 5, file );
我使用 ftell ( file );
得到 ftell 回傳值, 這兩個都一樣, 而 fread 回傳值不同
這兩個寫法有甚麼差異?
在檔案上又有甚麼影響?
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版)
#include "stdafx.h"
#define BUFFER_SIZE 10
int main( int argc, char *argv[] )
{
FILE *input_file1, *input_file2;
input_file1 = fopen( argv[1], "rb" );
input_file2 = fopen( argv[2], "rb" );
unsigned char inp_buf1[BUFFER_SIZE];
unsigned char inp_buf2[BUFFER_SIZE];
fseek( input_file1, 0, SEEK_SET );
fseek( input_file2, 0, SEEK_SET );
printf( "fread1 = %d, ", fread( inp_buf1, 2, BUFFER_SIZE / 2, input_file1 ) );
printf( "ftell1 = %d\n", ftell( input_file1 ) );
printf( "fread2 = %d, ", fread( inp_buf2, 1, BUFFER_SIZE, input_file2 );
printf( "ftell2 = %d\n", ftell( input_file2 ) );
return 0;
}
補充說明(Supplement):
argv[1] 是 argv[2] 的複製檔案, 名稱不同, 檔案內容相同
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.235.201.220
→ Feis:fread 的回傳值是跟count有關,去查一下。 12/01 17:10
→ andice780101:恩, 我只是不懂的地方在於那兩個寫法有甚麼差? 12/01 18:55
→ andice780101:在 ftell 回傳值好像都一樣 12/01 18:56
→ Feis:那你懂 fread 的回傳值了嗎? 為什麼會不同? 如果個數不夠呢? 12/01 19:10
→ Feis:實作上可能 fread 讀到的個數不到給的 count 12/01 19:10
→ Feis:你確定你查過回傳值了嗎? 12/01 19:11
→ andice780101:恩, fread 回傳值表示是 count 所讀到的值 12/01 19:51
→ andice780101:不夠時, 則讀到檔案末端 12/01 19:52
→ andice780101:我了解的是這兩個寫法, 對檔案而言, 不都是讀10byte? 12/01 19:53
→ Feis:為什麼? 如果檔案只有 9 bytes呢 ? 12/01 19:54
→ Feis:主要問題是語意還有當檔案內個數不足時, 可能可以怎麼處理 12/01 20:18
→ Feis:如果只有 9 bytes, 那第二種寫法的最後 1 byte 會讀進來嗎? 12/01 20:19
→ Feis:標準是用 indeterminate 這個字表示都有可能 12/01 20:20
→ Feis:上面那篇強調是語意部分, 實作部分的話則沒提 12/01 20:26
→ Feis:只是就我所知 glibc 內的實作都會把那 byte 讀進來 12/01 20:30
→ andice780101:抱歉~我只是在Windows下寫個讀寫檔小程式練習而已 12/01 21:54
→ andice780101:遇到一些指令, 並沒有很瞭解說真正使用的方式 12/01 21:55
→ andice780101:所以想請教有使用過的老手的看法是如何 12/01 21:56