struct book{
int code;
char title[20];
char author[20];
char publisher[20];
char year[4];
double price;
};
struct book book1, mybook[100];
FILE *tf, *bf;
int main(){
int i;
tf = fopen("mybook.txt","r");
bf = fopen("myEbooks","wb");
for(i=1; i<100; i++){
fscanf(tf,"%i\n", &book1.code);
fscanf(tf,"%[^\n]\n", book1.title);
fscanf(tf,"%[^\n]\n", book1.author);
fscanf(tf,"%[^\n]\n", book1.publisher);
fscanf(tf,"%[^\n]\n", &book1.year);
fscanf(tf,"%lf\n", &book1.price);
fwrite(&book1, sizeof(struct book),1, bf);
}
printf("\nBinary Stock file successfully generated!!\n");
fclose(tf);
fclose(bf);
return 0;
}
以上代碼用於從讀取.txt文件生成二進制文件。下面的代碼用於讀取二進制文件。如何顯示價格低於70.00的所有書籍。從閱讀文件?
struct book{
int code;
char title[20];
char author[20];
char publisher[20];
char year[4];
double price;
};
int main(){
int data;
int record;
double price;
struct book book1;
FILE * bf;
bf = fopen("myEbooks", "rb");
fseek(bf,1,SEEK_END);
record = (ftell(bf)/sizeof(struct book));
rewind(bf);
printf("Title\t\t Code\t\tAuthor\t\tPublisher\t Year\tPrice\n");
for(data=0;data<100;data++){
fread(&book1, sizeof(struct book), 1, bf);
printf("%s\t\t %i\t %s\t %s\t %s\t %0.2lf\n", book1.title, book1.code, book1.author, book1.publisher, book1.year, book1.price);
}
fclose(bf);
return 0;
}
- 如何插入的條件?
- 我需要在哪裏插入條件語句?
- 如何僅顯示價格低於70.00的圖書。從閱讀文件?
考慮將'myEbooks'文件的一部分與您的問題一起發佈,以便人們可以測試您的代碼! – hmofrad
如果您可以在mybook.txt中添加數據,這樣會更好,這樣我們就可以重現代碼並執行所需的特定更改。它在給你一個準確和正確的答案中扮演着重要的角色。 –
如果結構定義位於兩個程序包含的頭文件中,那將會更好。通過這種方式,您可以確定兩個計劃都同意結構,並且他們同意這一點至關重要。我沒有看到任何區別,但從長遠來看,冒險出現差異將是愚蠢的。您不檢查任何I/O操作。尤其是,您不檢查讀取操作是否成功。 –