如何从非文本文件读取,修改结构?

时间:2018-10-30 09:55:52

标签: c struct file-io

我想将一些结构保存到文件中,然后全部读取或修改。我尝试过这种方法,但是通过这种方式,我只得到了最后保存的结构,而且我不知道如何获取所有结构,或者以后如何在文件中修改它们。

仅最后保存的结构我没有收到任何错误,但是如果使用文本编辑器打开,在文件中我会看到所有错误。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <time.h>

#define MAX_STRING_LEN 80
#define PHONE_NUMBER 15

struct order {
    time_t   systime;
    char     name[MAX_STRING_LEN];
    char     email[MAX_STRING_LEN];
    int      phonenumber;
    int      size;
};


//functions
void saveToFiles(struct order *current);
void dbList(struct order *current);

//save into file
void saveToFiles(struct order *current) {
    FILE * file=fopen("db.txt", "a");
    if(file != NULL) {
        fwrite(current, sizeof(struct order), 1, file);
        //      fwrite("\n", sizeof("\n"), 1, file);   //If I broke the line then all of the reading get some numbers, without any meaning
        fclose(file);
    }
}

//list the db
void dbList(struct order *current) {
    int option;
    printf("list: \n    1 - ful list\n    2 - just names\n    3 - just size\n    0 - exit");
    scanf(" %i", &option);
    if(option == 0) {
        exit(1);
    }
    if(option == 1) {
        //loadList(1);
        struct order *obj=malloc(sizeof(struct order));
        FILE * file = fopen("db.txt","rb");
        fseek(file, 0, SEEK_SET);  //I tried to put the file read at the begining of the file
        while(fread(obj, sizeof(struct order), 1, file)) {
            printf("LOG: op1\n");
            fread(obj, sizeof(struct order), 1, file);
            printf("%s/%s/%d/%d\n", obj->name, obj->email, obj->phonenumber, obj->size);
        }
        if(feof(file)) {
            printf("\n--END--\n");
        }
        else {
            printf("Some error...");
        }
    }
}

//***

int main(k)
{
    struct order current;   //struct init
    //    current = malloc(sizof(*current));

    int option = 1;
    while(option != 0) {
        printf(" " "\x1B[34m");
        printf("0 exit \n 1 new \n 2 list \n \n " "\x1B[0m");
        scanf(" %i", &option);
        if(option == 1) {
            getNewOrder(&current);
        }
        if(option == 2) {
            dbList(&current);
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

对于写文件,请检查fseek()是否为SEEK_END,然后执行fwrite可以帮助您。