Stuck with fread function. There is a queue implemented through the list:

struct Bus_Info { char b_n[9]; char name[15]; char way[4]; int parking; int lesion; }; struct List { struct Bus_Info bus_info; int size; struct List * next; }; 

It is necessary to implement the reading of data from the file and add them to the queue. As I understand it:

 int main() { struct List * first;//указатель на начало очереди struct List * last;//указатель на конец очереди first = NULL; last = first; FILE *fp; fp = fopen("Bus_Info.dat","r"); if (fp==NULL) { printf("Its impossible to open"); return 1; } И в этом месте нужно описать fread() так что бы он считывал данные в структуру, и добавлять элемент в список пока не дойдем до конца файла. Как это возможно осуществить? return 0; } 

    1 answer 1

    You can open the file in binary mode and read one by one structure

      size_t size; struct Bus_Info * buf = malloc(sizeof(struct Bus_Info)); fp = fopen("Bus_Info.dat","rb"); size = fread(buf,sizeof(struct Bus_Info),1,fp); 

    If the structure is static and read / write occurs programmatically, I would do so.

     struct Bus_Info { char b_n[9]; char name[15]; char way[4]; int parking; int lesion; }__attribute__((packed)); struct Bus_Info * begin_list; struct Bus_Info * current; int amount = 0; int main(int argc,char * argv[]) { int rc; FILE *fp; struct stat st; stat("Bus_Info.dat",&st); amount= st.size; if(amount == 0){ return 1; } if(!(amount % (sizeof(struct Bus_Info)))){ /*ошибка файла*/ return 1; } begin_list = malloc(amount); fp = fopen("Bus_Info.dat","rb"); if (fp==NULL){ printf("Its impossible to open"); return 1; } rc = fread(begin_list,amount,1,fp); if(rc != amount){ /*ошибка чтения*/ return 1; } /*получаем колличество элементов и указатель на первый элемент*/ amount /= sizeof(struct(Bus_Info)); current = begin_list; /*смешение на любую структуры*/ current += number; /*доступ к элементам */ current->b_n; current->name; return 0; } 
    • It will not work, since those fields that are arrays in the structure are not required to have full length. - Zealint
    • @Zealint field length is small when writing to a file to zero. And when reading there will be zeros. For a small line is not critical. - Yaroslav
    • __attribute __ ((packed)); not quite clear what it is? - V. Rotenberh
    • __attribute __ ((packed)) This attribute tells the compiler not to align structures. Ie in a 32-bit system, the structure will occupy 36 bytes. And without this attribute in a 32-bit system, the structure will be aligned by 4 bytes and take 40 bytes. - Yaroslav