[英]Problem with the first character of the binary file while reading it in a C file
我正在嘗試讀取二進制文件及其內容。
/*aoObj.fb is the pointer of the file (e.x. FILE *fp)*/
char ch;
aoObj.fp = fopen(aoObj.f_name, "rb");
if (aoObj.fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* /\*list all strings *\/ */
printf("\n\nThe content of the file: \n");
while ((ch = fgetc(aoObj.fp)) != EOF)
printf("%c", ch);
fclose(aoObj.fp);
(void) opt_free(&aoObj);
return 0;
}
但是當我打印這個文件的內容時我遇到了問題,因為只有輸入的第一個字符沒有打印好,如下所示:
我可以知道為什么會這樣嗎?
編輯:正在讀取的所有變量都聲明為字符串
OP 聲明文件內容是“二進制”而不是“文本”因此,訪問文件應該通過為二進制文件制作的 I/O 操作符,
建議:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
由於從“二進制”文件讀取的數據不是 ascii 字符,因此嘗試使用“輸出格式轉換”說明符打印那些“二進制”字符是一個“錯誤”: %c
。
建議:
printf( "%02x\n", ch );
注意: %02x
因此將打印而不是抑制 0x0 的前導半字節。
當代碼被更正以使用: fread()
而不是fgetc()
時, ch
的聲明可以/應該是unsigned char ch;
因此無需將其更改為int ch;
以下建議的代碼:
main()
function 和參數的傳遞: f_name
所以不鏈接fread()
的返回值來“假設”EOF,但是,檢查errno
的值以確保沒有其他錯誤可能是有益的(並且對於健壯的代碼)。注意:建議的代碼效率不高,因為它一次只讀取一個字節,而不是一個充滿字節的整個緩沖區
注意:建議的代碼將 output 單行上的一個字節內容(十六進制)。 在移動到新行之前,您可能需要將其修改為 output 幾個字節內容(十六進制)。
現在,建議的代碼:
#include <stdio.h> // FILE, fopen(), perror(), printf(), fclose()
// fread()
#include <stdlib.h> // exit(), EXIT_FAILURE
void myfunc( char *f_name )
{
unsigned char ch;
FILE *fp = fopen( f_name, "rb");
if (fp == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* /\*list all strings *\/ */
printf("\n\nThe content of the file: \n");
size_t bytesRead;
while ( ( bytesRead = fread( &ch, 1, 1, fp ) ) == 1 )
{
printf("%02x\n", ch);
}
fclose(fp);
}
您將ch
聲明為char
但您應該將其聲明為int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.