如何将结构从二进制文件写入另一个二进制文件中的嵌套结构?

时间:2019-05-14 20:34:14

标签: c file struct binaryfiles fwrite

我有这个代码。假设我想将排期1(由InputFlight函数生成)链接到用户1(由InputUser函数生成)。 注意:结构 user 具有另一个名为 booking 的嵌套结构,该结构具有名为 飞行

通过在二进制文件中移动指针,我要做的是:

向用户询问一个航班号(假设是第一个航班)->所以我转到第一个航班。

询问用户他是哪个用户(假设第一个用户)->因此,我移到第一个用户。

然后通过 fread() fwrite(),我尝试复制结构 flight 中的内容进入 travelers.b.list ,但以某种方式无法正常工作。

我已经尝试了一切。我尝试在 fwrite() fseek()中更改参数,但没有成功。我想主要的问题是在booking.h中的函数 checkin()中,但是我似乎无法解决。

main.c

#include <stdio.h>
#include <stdlib.h>

#include "flight.h"
#include "user.h"

void login_admin();

int main() {
    setbuf(stdout, NULL);

    login_admin();

return 0;
}

void login_admin() {

    FILE *file;
    FILE *file1;

    unsigned short int userchoice1 = 0;
    unsigned short int s = 0;

    while (s != 1) {    
        printf("\n-------------- M E N U --------------");
        printf("\n----- A D M I N I S T R A T O R -----");
        printf("\n1) Insert user");
        printf("\n2) Insert flight");
        printf("\n3) Check-in");
        printf("\n9) Exit program");
        printf("\n-------------------------------------");
        printf("\nYOUR CHOICE: ");
        scanf("%hu", &userchoice1);

        if (s != getchar()) {
        }
        switch (userchoice1) {
        case 1:
            inputUser(file);
            break;
        case 2:
            inputFlight(file);
            break;
        case 3:
            checkin(file, file1);
            break;
        case 9:
            s = 1;
            exit(0);
            break;
        default:
            printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
            printf("\nValue not valid.");
            break;
        }
    }
}

booking.h

#include <stdio.h>

 typedef struct {
    flight list;
    char booking_code[MAX_BOOKING_CODE];
} booking; //struct booking

 typedef struct {
    char name[MAX_NAME];
    char surname[MAX_SURNAME];
    date date_of_birth;
    char place_of_birth[MAX_PLACE_OF_BIRTH];
    char passport_number[MAX_PASSPORT];
    booking b;
 } user; //struct user

void checkin(FILE *flights, FILE *users) {

    flight list;
    user travelers;

    int user_number = 0;
    int choice = 0;
    int choice1= 0;

    if( (users = fopen("users.dat", "rb") ) == NULL) {
        printf("Error.(1)");
    }
    else
    {
        printf("\nWhat's your user number?");
        printf("\nUSER NUMBER: ");
        scanf("%d", &user_number);
        fseek(users, (user_number-1)*sizeof(user), SEEK_SET);
        fread(&travelers, 1, sizeof(user), users);

        if( (flights = fopen("flights.dat", "rb") ) == NULL) {
            printf("Error.");
        }
        else {
            printf("Available flights:\n\n");

                flights = fopen("flights.dat", "rb");

                while( !(feof(flights)))
                {

                int read = fread(&list, 1, sizeof(flight), flights);
                if ( read > 0) {
                    printf("Flight code: %s\nCompany name: %s\nDEPARTURE FROM: %s\nARRIVAL AT: %s\nPlane code: %s\nDay of flight: %hu\nMonth of flight: %hu\n"
                            "Year of flight: %hu\nHour of departure: %hu:%hu\nHour of arrival: %hu:%hu\nFlight time: %hu min.\n\n",
                            list.flight_code, list.companyname, list.departure,
                            list.arrival, list.plane_code, list.date_of_flight.day,
                            list.date_of_flight.month, list.date_of_flight.year, list.hour_departure,
                            list.minute_departure,list.hour_arrival,list.hour_departure, list.flight_time);
                }

            }

            printf("Which flight you want to choose?\n");
            printf("YOUR CHOICE: ");
            scanf("%d", &choice1);

            fseek(flights, (choice1-1)*sizeof(flight), SEEK_SET);
            fread(&list, 1, sizeof(flight), flights);

            printf("\n--------YOU CHOSE FLIGHT %d-------- \n\n", choice1);
                    printf("Flight code: %s\nCompany name: %s\nDEPARTURE FROM: %s\nARRIVAL AT: %s\nPlane code: %s\nDay of flight: %hu\nMonth of flight: %hu\n"
                            "Year of flight: %hu\nHour of departure: %hu:%hu\nHour of arrival: %hu:%hu\nFlight time: %hu min.\n\n",
                            list.flight_code, list.companyname, list.departure,
                            list.arrival, list.plane_code, list.date_of_flight.day,
                            list.date_of_flight.month, list.date_of_flight.year, list.hour_departure,
                            list.minute_departure,list.hour_arrival,list.hour_departure, list.flight_time);


            users = fopen("users.dat", "rb+");
            fseek(users, (user_number-1)*sizeof(user), SEEK_SET);

            fwrite(&travelers.b.list, 1, sizeof(user), users);

            fclose(users);
            fclose(flights);

flight.h

#include <stdio.h>
#include "define.h"

typedef struct {
    unsigned short int day;
    unsigned short int month;
    unsigned short int year;
 } date; //struct date

 typedef struct {
    char flight_code[MAX_FLIGHT_CODE];
    char companyname[MAX_COMPANY_NAME];
    char departure[MAX_DEPARTURE];
    char arrival[MAX_ARRIVAL];
    char plane_code[MAX_PLANE_CODE];
    unsigned short int seats[MAX_SEATS];
    date date_of_flight;
    unsigned short int hour_departure;
    unsigned short int minute_departure;
    unsigned short int hour_arrival;
    unsigned short int minute_arrival;
    unsigned short int flight_time;
} flight; //struct flight

void inputFlight(FILE *flight_file);

void inputFlight(FILE *flight_file) {

    flight list;

    static int i = 0;

    //for (int i = 0; i < 20; i++) {

        flight_file = fopen("flights.dat","wb");
        printf("Flight code %d: ", i+1);
        scanf("%6s", list.flight_code);
        fflush(stdin);
        printf("Company name of flight %d: ", i+1);
        scanf("%19s", list.companyname);
        fflush(stdin);
        printf("DEPARTURE: ");
        scanf("%19s", list.departure);
        fflush(stdin);
        printf("ARRIVAL: ");
        scanf("%19s", list.arrival);
        fflush(stdin);
        printf("Plane code of flight %d: ", i+1);
        scanf("%4s", list.plane_code);
        fflush(stdin);
        printf("Day of flight %d: ", i+1);
        scanf("%hu", &list.date_of_flight.day);
        fflush(stdin);
        printf("Month of flight %d: ", i+1);
        scanf("%hu", &list.date_of_flight.month);
        fflush(stdin);
        printf("Year of flight %d: ", i+1);
        scanf("%hu", &list.date_of_flight.year);
        fflush(stdin);
        printf("Hour and minutes of departure flight %d (separated by spacebar): ", i+1);
        scanf("%hu%hu", &list.hour_departure, &list.minute_departure);
        fflush(stdin);
        printf("Hour and minutes of arrival flight %d (separated by spacebar): ", i+1);
        scanf("%hu%hu", &list.hour_arrival, &list.minute_arrival);
        fflush(stdin);
        printf("Flight time: ");
        scanf("%hu", &list.flight_time);
        fflush(stdin);

        fwrite(&list, 1, sizeof(flight), flight_file);

        fclose(flight_file);

    //}
}

user.h

#include <stdio.h>
#include <stdlib.h>
#include "booking.h"

void inputUser(FILE *input);

void inputUser(FILE *input) {


    if( (input = fopen("users.dat", "wb") ) == NULL) {
        printf("Error.");
    }
    else {

        user travelers;

        static int i = 0;

        //for (int p = 0; p < 3; p++) {

            printf("Name user %d: ", i+1);
            scanf("%19s", travelers.name);
            fflush(stdin);
            printf("Surname user %d: ", i+1);
            scanf("%19s", travelers.surname);
            fflush(stdin);
            printf("Day of birth user %d: ", i+1);
            scanf("%hu", &travelers.date_of_birth.day);
            fflush(stdin);
            printf("Month of birth user %d: ", i+1);
            scanf("%hu", &travelers.date_of_birth.month);
            fflush(stdin);
            printf("Year of birth user %d: ", i+1);
            scanf("%hu", &travelers.date_of_birth.year);
            fflush(stdin);
            printf("Place of birth user %d: ", i+1);
            scanf("%9s", travelers.place_of_birth);
            fflush(stdin);
            printf("Passport number user %d: ", i+1);
            scanf("%8s", travelers.passport_number);
            fflush(stdin);

            fwrite(&travelers, 1, sizeof(user), input);
            i++;

        //}

        fclose(input);
    }
}

define.h

#ifndef DEFINE_H_
#define DEFINE_H_

#define MAX_NAME 20
#define MAX_SURNAME 20
#define MAX_PASSPORT 9
#define MAX_PLACE_OF_BIRTH 15

#define MAX_FLIGHT_CODE 6
#define MAX_COMPANY_NAME 20
#define MAX_DEPARTURE 20
#define MAX_ARRIVAL 20
#define MAX_PLANE_CODE 5
#define MAX_SEATS 150

#define MAX_BOOKING_CODE 5

#endif /* DEFINE_H_ */

预期结果是结构 list 通过功能 checkin()中的 fseek()查找(基本选择) strong>应该保存在结构 travelers.b.list 中,而当我尝试打印时,得到的只是各种符号的组合。

希望我能为您弄清楚一切,对于格式错误等问题,请提前见谅。

这对我来说是一个非常大的大学项目,希望有人能帮助我。

谢谢。

1 个答案:

答案 0 :(得分:1)

在inputUser中,您正在编写

fwrite(&travelers, 1, sizeof(user), input);

似乎更合乎逻辑

fwrite(&travelers, sizeof(user), 1, input);

因为 fwrite

  

size_t fwrite(const void * ptr,size_t size,size_t nmemb,FILE * stream);

而不是

  

size_t fwrite(const void * ptr,size_t nmemb,size_t size,                        FILE * stream);

当然其他地方也一样,例如 checkIn ,对于 fread ,您还可以交换 nmemb size < / em>


请注意,在签入中您进行了两次flights = fopen("flights.dat", "rb")

    if( (flights = fopen("flights.dat", "rb") ) == NULL) {
        printf("Error.");
    }
    else {
        printf("Available flights:\n\n");

            flights = fopen("flights.dat", "rb");

因为使用相同的变量 flights ,所以只能关闭第二个FILE。一段时间后,您将无法再次打开文件,因为同时打开的文件数受到限制。


警告

 while( !(feof(flights)))

通常does not work,使用 fread 的结果停止读取


您可以删除所有fflush(stdin);,但它们什么也不做:

  

对于与可搜索文件(例如磁盘文件,          但不是管道或终端),fflush()会丢弃所​​有缓冲的数据...


我建议您检查 scanf 的结果以确保输入了有效的输入,因此要检查它在读取值时返回1,在少数情况下则读取2个值,则返回2 < / p>

   scanf("%d", &user_number);
   fseek(users, (user_number-1)*sizeof(user), SEEK_SET);
   fread(&travelers, 1, sizeof(user), users);

       scanf("%d", &choice1);

       fseek(flights, (choice1-1)*sizeof(flight), SEEK_SET);
       fread(&list, 1, sizeof(flight), flights);

根本没有检查

因此您不知道所读内容,您假设为user_numberchoice1输入了一个有效的 int ,您假设它们的值与文件,那么您假设您可以阅读 user / fligh

您确实需要添加支票


  

我想主要的问题是在booking.h中的功能checkin()

是的,在签入中,您修改用户航班档的方法不正确,您这样做

 fseek(users, (user_number-1)*sizeof(user), SEEK_SET);

 fwrite(&travelers.b.list, 1, sizeof(user), users);

fseek 设置文件中用户开始的位置,而不是 fwrite 的所有用户> fwrite 子部分travelers.b.list,以便您将 name / surname /...替换为航班号(及其后的内存,因为您写的是用户的大小而不是的大小)),由于您以前在变量 list 中而不是在travelers.b.list中变量 fread ,因此未初始化。

一种纠正方法是先更新travelers.b.list然后写所有用户,然后替换

       fread(&list, 1, sizeof(flight), flights);

       printf("\n--------YOU CHOSE FLIGHT %d-------- \n\n", choice1);
               printf("Flight code: %s\nCompany name: %s\nDEPARTURE FROM: %s\nARRIVAL AT: %s\nPlane code: %s\nDay of flight: %hu\nMonth of flight: %hu\n"
                       "Year of flight: %hu\nHour of departure: %hu:%hu\nHour of arrival: %hu:%hu\nFlight time: %hu min.\n\n",
                       list.flight_code, list.companyname, list.departure,
                       list.arrival, list.plane_code, list.date_of_flight.day,
                       list.date_of_flight.month, list.date_of_flight.year, list.hour_departure,
                       list.minute_departure,list.hour_arrival,list.hour_departure, list.flight_time);


       users = fopen("users.dat", "rb+");
       fseek(users, (user_number-1)*sizeof(user), SEEK_SET);

       fwrite(&travelers.b.list, 1, sizeof(user), users);

作者

        fread(&travelers.b.list, sizeof(flight), 1, flights);

        printf("\n--------YOU CHOSE FLIGHT %d-------- \n\n", choice1);
                printf("Flight code: %s\nCompany name: %s\nDEPARTURE FROM: %s\nARRIVAL AT: %s\nPlane code: %s\nDay of flight: %hu\nMonth of flight: %hu\n"
                        "Year of flight: %hu\nHour of departure: %hu:%hu\nHour of arrival: %hu:%hu\nFlight time: %hu min.\n\n",
                        travelers.b.list.flight_code, travelers.b.list.companyname, travelers.b.list.departure,
                        travelers.b.list.arrival, travelers.b.list.plane_code, travelers.b.list.date_of_flight.day,
                        travelers.b.list.date_of_flight.month, travelers.b.list.date_of_flight.year, travelers.b.list.hour_departure,
                        travelers.b.list.minute_departure,travelers.b.list.hour_arrival,travelers.b.list.hour_departure, travelers.b.list.flight_time);


        users = fopen("users.dat", "rb+");
        fseek(users, (user_number-1)*sizeof(user), SEEK_SET);

        fwrite(&travelers, sizeof(user), 1, users);

更接近代码的另一种方法是在正确的位置 fseek 并以正确的大小编写正确的排行,以便替换

 fseek(users, (user_number-1)*sizeof(user), SEEK_SET);

 fwrite(&travelers.b.list, 1, sizeof(user), users);

作者

 fseek(users, (user_number-1)*sizeof(user) + (((char *) &travelers.b.list) - ((char *) &travelers)), SEEK_SET);

 fwrite(&list, sizeof(list), 1, users);