簡體   English   中英

如何使用fread()讀取二進制文件

[英]How to read a binary file with fread()

我正在編寫一個必須遍歷二進制文件並將其寫入文本文件的函數。 二進制文件的每一行都包含
l1名l2姓ID GPA
例)瑪麗·喬瑟夫1234 4.0

其中l1和l2分別是名字和姓氏的長度,ID是一個無符號的int,而GPA是一個浮點數(每個4個字節)。
如何正確實現循環遍歷二進制文件,直到到達EOF? 目前,生成的文本文件大部分都是亂碼,我該如何解決? 任何幫助表示贊賞。

int binaryToText() //add parameters
{

unsigned char firstName[255];
unsigned char lastName[255];
unsigned int id;
float gpa;
char nLine[]= "\n";
char space[]= " ";


FILE * binfile = fopen("b2.bin", "r"); //Open and read binary file binfile
FILE * textfile = fopen("b2totxt.txt", "w");//Open and write to text file



if(NULL == binfile) //alerts and exits if binfile is not found
{
    fprintf(stderr, "Failed to open file\n");
    fflush(stderr);
    exit(1);
}


fread(&firstName, sizeof(firstName), 1, binfile);
fread(&lastName, sizeof(lastName), 1, binfile);
fread(&id, sizeof(id), 1, binfile);
fread(&gpa, sizeof(gpa), 1, binfile);

printf("%s %s %u %f", firstName, lastName, id, gpa); //test(doesnt come out right)

fprintf(textfile, "%s %s %u %1.1f\n", firstName, lastName, id, gpa);//also flawed





fclose(textfile);
fclose(binfile); //close bin file
return 0;

}

您想讀取二進制數據,但是,您的文件已打開以讀取文本"r" ),而不是讀取二進制"rb" )。 因此, fread()可能會將"\\r\\n""\\n" ,當特定的unsigned intfloat值的基礎表示形式包含"\\r\\n"序列時,這可能會引起問題。

更改此:

FILE * binfile = fopen("b2.bin", "r");

對此:

FILE * binfile = fopen("b2.bin", "rb");

"rb"b代表二進制模式。


但是,我認為這不是您的主要問題,因為您的二進制文件實際上並不包含數據的二進制表示形式。 它包含人類可讀的表示形式 (基於您給出的示例)。 您應該使用fscanf而不是fread來讀取該數據。

更改此:

fread(&firstName, sizeof(firstName), 1, binfile);
fread(&lastName, sizeof(lastName), 1, binfile);
fread(&id, sizeof(id), 1, binfile);
fread(&gpa, sizeof(gpa), 1, binfile);

對此:

int n = fscanf(binfile, "%s %s %u %f", firstName, lastName, &id, &gpa);

FILE * binfile = fopen("b2.bin", "r");

這應該是

FILE * binfile = fopen("b2.bin", "rb"); 打開任何二進制文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM