c - 如何从非文本文件中读取、修改结构?

标签 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;
}

最佳答案

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

关于c - 如何从非文本文件中读取、修改结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53061633/

相关文章:

iOS:保存到文件中可以在模拟器上使用,但不能在设备上使用

c++ - 如何在 C 中包含第三方库?

c - 如何在宏字符串中嵌入一个整数?

c++ - 尝试在 OS X 上为 32 位和 64 位编译 GNU 库

c++ - 具有结构 vector 的类,其中包含相同的类

c - 在C中通过地址传递struct-within-pointer-array-within-struct

c - 连接字符串时获得不必要的值

C迭代结构数组

c - 为什么这个简单的 c 代码片段不起作用

C:链表并写入文件