c - 在 C 中将行(来自结构体)动态分配到文件中

标签 c

我会尽力做到快速、清晰。我想做的是一种“数据库”,链式餐厅有很多位置。

程序以二进制形式写入文件“sedi.dat”,该文件在程序中用 100 个空记录初始化,这些记录引用结构“ristorante”

typedef struct {
    int codice;
    char sede[12];
    int posti, liberi, occupati;
} ristorante;

ristorante buffer = { 0, "", 0, 0, 0};
//fopen stuff
for (i=0; i<100; ++i) {
    fwrite(&buffer, sizeof(ristorante), 1, pointer);
};

现在我有 100 个二进制行,基本上是 { 0, "", 0, 0, 0};。我想要对这个“格式化”文件执行的操作是用用户输入的行填充它。

我创建了一个函数来执行此操作 void create_table (FILE *pointer);它基本上(应该)做的是接收文件指针,创建2个空缓冲区(我用它来存储来自输入和文件的数据,但我可以更改它)然后循环直到指针到达文件末尾或内部的if该循环给出flag=1(当找到以结构体中第一个0开始的行时会发生这种情况),否则它会增加计数器并移动偏移量counter*sizeof(struct),然后加载用fread写入的内容! p>

现在,问题是这个函数只能加载第一行(多次尝试它只能写入第一行),它无法查找其他行!我想做的是:

read row
if (first value of struct!=0) {
    ++counter;
    seek next row
}
else {
    write input row with increasing first value starting from 1 to 100
}

我试了、试了、搜索了、试了两天,但现在是时候寻求帮助了! 程序菜单

  1. 打印所有行(我消除了一个if,如果行为空则不打印)
  2. 插入新行
  3. 必须进一步检查才能正常工作
  4. 退出

希望我已经说清楚了,现在我在你的手中:)

这是完整的代码:

#include <stdio.h>
#include <stdlib.h>
#define def 100

typedef struct {
    int codice;
    char sede[12];
    int posti, liberi, occupati;
} ristorante;

typedef struct {
    int number, posti, codice;
} prenotazione;

int scelta_menu (void);
int new_prenotazione (prenotazione max, FILE *pointer, int i);
void stampa_tabella (FILE *pointer);
void create_table (FILE *pointer);


int main () {
    prenotazione max; 
    int scelta, i;
    int conta_entry=0;
    FILE *pointer;
    ristorante buffer = { 0, "", 0, 0, 0};

    while((scelta=scelta_menu())!=5) {
        if((pointer=fopen("sedi.dat", "rb+"))==NULL)  {

            printf("\nTabella sedi assente, ne verra' creata una nuova.\n\n");
            pointer=fopen("sedi.dat", "wb+");

            for (i=0; i<def; ++i) {
                fwrite(&buffer, sizeof(ristorante), 1, pointer);
            }

        }
        else {
            printf("\nFile caricato con successo!");

            switch (scelta) {

            case 1: 
                 stampa_tabella(pointer);
                 break;

            case 2: 
                 create_table(pointer);
             break;

            case 3: 
                 conta_entry=new_prenotazione(max, pointer, conta_entry);
                 break;

         case 4: 
                  printf("La prenotazione con il maggior numero di posti e' la #%d per #%d posti\n\n", max.codice, max.posti);
                  break;

         default:
                  printf("\nScelta non corretta!\n\n");
                  break;

            }

        }

        fclose(pointer);

    }
    return 0;
}



int scelta_menu (void) {
    //system("cls");
    int scelta;
    printf("\n\nMenu Prenotazione:\n\n1 - Visualizza Tabella\n2 - Crea/Aggiorna Tabella\n3 - Nuova prenotazione\n4 - Visualizza prenotazione  piu' grande\n5 - Esci\n\n---> ");
    scanf("%d", &scelta);

    return(scelta);
}

void create_table (FILE *pointer) {

    int i=0;
        int flag=0;
ristorante buffer = { 0, "", 0, 0, 0};

    ristorante buffer1 = { 0, "", 0, 0, 0};

    printf("\nInserisci il nome della sede ed il numero totale dei posti: ");

    scanf("%s%d", buffer.sede, &buffer.posti);
buffer.liberi=buffer.posti;

    printf("\n\n\n%-6s%8s        %s     %s      %s\n", "Cod.", "Sede", "Posti", "Occupati", "Liberi");

    printf("%-6d%10s         %d         %d             %d\n", buffer.codice, buffer.sede, buffer.posti, buffer.occupati, buffer.liberi);

     do {

        fread(&buffer1, sizeof(ristorante), 1, pointer);

        if (buffer1.codice!=0) {

        flag=0;

        ++i;

        fseek(pointer, (i)*sizeof(ristorante), SEEK_SET);

        }

        else {

        flag=1;

        printf("\nEsisto...\n");

        buffer.codice=buffer1.codice+1;

        fwrite(&buffer, sizeof(ristorante), 1, pointer);

        }

    } while(!feof(pointer) && flag!=1);

     fclose(pointer);

     system ("pause");
}



    void stampa_tabella (FILE *pointer) {

    ristorante buffer = { 0, "", 0, 0, 0};

    printf("\n\n\n%4s%8s        %s     %s      %s\n", "Cod.", "Sede", "Posti", "Occupati", "Liberi");

    while(!feof(pointer)) {

     //fseek(pointer, i*sizeof(ristorante), SEEK_SET);

     fread(&buffer, sizeof(ristorante), 1, pointer);

     // if (buffer.codice!=0) {
 printf("%d%10s         %d         %d             %d\n", buffer.codice, 

     buffer.sede, buffer.posti, buffer.occupati, buffer.liberi);

    //}
     }

    fclose(pointer);
    } //fine stampa tabella
    int new_prenotazione (prenotazione max, FILE *pointer, int i) {
prenotazione buffer;
ristorante rist;


    printf("\nInserisci il codice della sede ed il numero dei posti da prenotare: ");
        scanf("%d%d", &buffer.codice, &buffer.posti);
        //sposto puntatore file

    fseek(pointer, (buffer.codice)*sizeof(ristorante), SEEK_SET);

    //legge record

    fread(&rist, sizeof(ristorante), 1, pointer);

    // errore se la sede non esiste

    if(rist.codice!=buffer.codice) {

        printf("\n\nLa sede %d non esiste!\n\n", buffer.codice);

     }

     //altrimenti aggiorna il record del file sede


       else {

      ++i;

        buffer.number=i;

        rist.liberi-=buffer.posti;

        rist.occupati+=buffer.posti;

        printf("\nPrenotazione effettuata! ");

        printf("\nCodice Sede Posti Occupati Liberi\n");

        fwrite(&rist, sizeof(ristorante), 1, pointer);
        }

    if(buffer.posti>=max.posti) {
            max=buffer;


      }


       rewind(pointer);
        return (i);
    } //fine new_record

     //end**

最佳答案

听起来您要求的是 random access file I/O 。与固定长度记录相结合,允许读取和写入文件中的各个条目,而无需读取/写入整个文件。您可能需要维护一个(或多个)显式索引来支持这一点。

注意:如果插入是指在现有条目之间插入,那就很困惑了。与数组一样,要插入一条记录,您必须首先将所有其他记录向上移动以为它腾出空间,这意味着读取并重写它们(并确保在此过程中不要让它们互相踩踏) .) 根据您正在执行的操作和原因,更好的答案可能是将新记录附加到文件末尾,并只关心索引中的排序。

可以通过从实时数据索引中删除记录并将其添加到“空记录”列表以便可能重用(而不是附加到文件末尾)来处理删除。

基本上,这是与内存管理和/或处理固定长度字符串数组相同的问题。

关于c - 在 C 中将行(来自结构体)动态分配到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867932/

相关文章:

c - 测试用户输入的字符串是否包含正则表达式

c - 关于 "object having more than one object representation"的未指定行为

c - C语言二维数组的动态内存分配

c - 为什么这个 switch 语句给出 11 作为输出?

c - 从 C 文件中读取整数

c - 读取双值 PIC18F67K22

c - ncurses下如何可靠地处理KEY_HOME和KEY_END

javascript - 如何在编译为WebAssembly的Rust库中使用C库?

c - C语言中的位与

用 C 语言为 IRC 机器人创建一个基本 shell,并在后台运行另一个线程