1. 程式人生 > >fread 返回 0

fread 返回 0

fread 函式一直返回 0,檢查過讀取的數量不會超過檔案大小,錯誤發生在開啟檔案時錯誤。

錯誤程式碼如下:

FILE *in_file, *out_file;
unsigned int open_files(const char *in_file_name, const char *out_file_name)
{
    if( in_file = fopen(in_file_name, "rb") == NULL)  //err
        return 0;

    if( out_file = fopen(out_file_name, "wb") == NULL) //err
        return
0; return 1; }

正確應該是:

FILE *in_file, *out_file;
unsigned int open_files(const char *in_file_name, const char *out_file_name)
{
    if( (in_file = fopen(in_file_name, "rb")) == NULL)
        return 0;

    if( (out_file = fopen(out_file_name, "wb")) == NULL)
        return 0;

    return 1;   
}

錯誤的原因在於沒有使用括號,而比較運算子 == 的優先順序比賦值運算子 = 要高。因此,錯誤的程式執行結果為,函式正常打開了檔案,返回的檔案指標與 NULL 相比為0,賦值給了 in_file, if 中的語句不會執行,因此誤以為 in_file 是檔案指標,實際上為0,所以無法讀出資料。