01/10/2018, 15:12
Đọc ghi file nhị phân trong C
#include "stdafx.h"
#include <string.h>
#include<conio.h>
#include <stdio.h>
struct studentfile {
char id[10];
char name[50];
float mark;
};
void input_student(studentfile &p)
{
printf("Enter ID: ");
gets_s(p.id, 10);
fflush(stdin);
printf("Enter Name: ");
gets_s(p.name, 50);
fflush(stdin);
printf("Enter mark: ");
scanf("%f", &p.mark);
}
void write_student(char filename[])
{
studentfile p;
FILE *f = fopen(filename, "wb");
if (f == NULL)
{
printf("open error!");
return;
}
fwrite(&p, sizeof(studentfile), 1, f);
fclose(f);
}
void read_student(char filename[])
{
studentfile p;
FILE *f = fopen(filename, "rb");
if (f == NULL)
{
printf("open error!");
return;
}
fread(&p, sizeof(studentfile), 1, f);
printf("ID: %s - Name: %s - Mark: %.2f", p.id, p.name, p.mark);
fclose(f);
}
int main(int argc, char*argv[])
{
char filename[50] = "student.bin";
studentfile p;
input_student(p);
write_student(filename);
read_student(filename);
_getch();
return 0;
}

MÌnh muốn sau khi nhập vào thông tin của sinh viên thì ghi thông tin đó vào file và đọc lại. Chương trình chạy ok. Nhưng sau khi đọc xong xuất ra màn hình toàn rác. Bác nào coi hộ lỗi chỗ nào với. Cảm ơn ạ.
Bài liên quan
Tại sao bạn phải dùng đến binary?
Mình thấy cứ để bình thường là được, thên binary làm gì cho mệt.
p đã có gì đâu mà ghi bạn
Vả lại, đây là code C++.[quote=“Vo_Duc_Dan, post:1, topic:65627”]
void input_student(studentfile &p)
[/quote]
Nhập p vào sau đó ghi vô file luôn mà.
Bạn nên đọc lại hàm
write_student
của bạn. Nó không như bạn nghĩ đâu.