201306181444fgets 改成 fread 資料讀取就會變正確

int main(int argc, char **argv)
{   
    int i = 0;
    uint32_t crc32_ret = 0;
    unsigned char buffer[100];
    unsigned char buffer_set[92];
    FILE *fp; 
    memset(buffer, 0, sizeof(buffer));
    memset(buffer_set, 0, sizeof(buffer_set));
    if (argc <= 2) {
        fp = fopen(argv[1], "r");
        if (!fp)
           return -1;
        if (fgets(buffer, sizeof(buffer)- 1, fp) == NULL)
            printf("Read ERROR!\r\n");       
        memcpy(buffer_set, buffer, sizeof(buffer_set));
        for(i = 0; i < 92; i++) {
            printf("The buffer_set[%d] is 0x%2x\r\n",i,buffer_set[i]);
        }       
     printf("The sizeof(buffer_set) is %d\r\n",(int)sizeof(buffer_set));      
     crc32_ret = HeaderCrc(buffer_set,sizeof(buffer_set));
     printf("The crc32 [1]  is 0x%2x\r\n",crc32_ret & 0xff );
     printf("The crc32 [2]  is 0x%2x\r\n",(crc32_ret >> 8) &  0xff );
     printf("The crc32 [3]  is 0x%2x\r\n",(crc32_ret >> 16) & 0xff );
     printf("The crc32 [4]  is 0x%2x\r\n",(crc32_ret >> 24) & 0xff );    
     fclose(fp);
     return 1;
    }
}


這個程式有個問題 , 就是當你所[餵進去]的資料裡面有 0A 的話程式會以為是換行
所捉的資料會亂掉
解釋如下 : ==>新行字元 (\n) 相當於在 ASCII 換行字元 (十六進位 0A)

所以程式比需修改如下才可以正確讀去資料
==> fgets 改成 fread 資料讀取就會變正確

int main(int argc, char **argv)
{   
    int i = 0;
    uint32_t crc32_ret = 0;
    unsigned char buffer[95];
    unsigned char buffer_set[92];
    FILE *fp; 
    memset(buffer, 0, sizeof(buffer));
    memset(buffer_set, 0, sizeof(buffer_set));
    if (argc <= 2) {
        fp = fopen(argv[1], "r");
        if (!fp)
         return -1;
        fseek(fp, 0L, SEEK_SET);
        fread(buffer, 1 , sizeof(buffer), fp);
        memcpy(buffer_set, buffer, sizeof(buffer_set));
        for(i = 0; i < 92; i++) {
            printf("The buffer_set[%d] is 0x%2x\r\n",i,buffer_set[i]);
        }
    printf("The sizeof(buffer_set) is %d\r\n",(int)sizeof(buffer_set));       
    crc32_ret = HeaderCrc(buffer_set,sizeof(buffer_set));
    printf("The crc32 [1]  T1 is 0x%2x\r\n",crc32_ret & 0xff ); 
    printf("The crc32 [2]  is 0x%2x\r\n",(crc32_ret >> 8) &  0xff );
    printf("The crc32 [3]  is 0x%2x\r\n",(crc32_ret >> 16) & 0xff );
    printf("The crc32 [4]  is 0x%2x\r\n",(crc32_ret >> 24) & 0xff );    
    fclose(fp);
    return 1;
    }

 

沒有上一則|日誌首頁|沒有下一則
回應





Powered by Xuite
    沒有新回應!
關鍵字