将结构写入文件C.

时间:2015-07-02 20:41:56

标签: c file struct fwrite

我刚刚开始学习文件。为此,我试图创建一个跟踪商店中交易记录的程序。第一步是记录一天的交易。我创建了一个文件trans.c,我可以在main.c文件旁边打开它,以便跟踪它。然后我首先使用空结构填充trans.c以为事务记录分配内存,然后使用fwrite将其填入包含客户端数据的结构。

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

/*
 * 
 */
struct clientData {
    int num;
    char fName [20];
    char lName[20];
    long double balance;

};

void createFiles (FILE *fNew, FILE *fOld, FILE *fTrans, struct clientData x);
void fillTrans (FILE *fTrans, struct clientData x);

int main() {

    FILE *fTrans; //transaction file
    FILE *fNew;  //new master file
    FILE *fOld;  //old master file 

    struct clientData blankClient = {0, "", "", 0.0 };


    if ((fTrans = fopen("trans.c", "wb")) == NULL) {
        printf("Error. File could not be opened.\n");
    }

    else {
        int i;
        for (i = 1; i <= 100; i++) {
         fwrite(&blankClient, sizeof(struct clientData), 1, fTrans);  
        }
    }

    fillTrans(fTrans, blankClient);

}

void fillTrans(FILE *fTrans, struct clientData x) {

    if ((fTrans = fopen("trans.c", "a+")) == NULL) {
        printf("File could not be opened.");
    }

    else {
        printf("Enter the account info, or 0 to quit.\n");
        scanf("%d%s%s%Lf", &x.num, x.fName, x.lName, &x.balance);

        while (x.num!= 0) {

            fseek(fTrans, (x.num - 1) * sizeof(struct clientData), SEEK_SET);
            fwrite(&x, sizeof(struct clientData), 1, fTrans);
            fscanf(stdin, "%d%s%s%Lf", &x.num, x.fName, x.lName, &x.balance);

        }

        fclose(fTrans);
    }
}

当我回到trans.c以查看它是否有效时,文件仍然是空的,但我的代码编译没有问题,并且在运行时我似乎无法填写结构和写下来。文件是否在其他地方填写,或者我错过了什么/做错了?

1 个答案:

答案 0 :(得分:1)

您正在打开&#34; trans.c&#34;在main中,然后调用fillTrans()而不先关闭它 - 所以当你在fillTrans()中写入数据时,你打开文件两次。如果您正在运行此设置的设置允许两个打开成功(在某些情况下,文件锁定会阻止它),那么最后关闭的设置可能确定文件的最终内容。由于main()没有关闭它(所以当程序结束时它的副本会关闭),你最终会得到main()放入文件中的内容并丢弃fillTrans()通过第二个FILE *

最终可能会从文件中fillTrans()部分结束(如果它没有附加),但文件大小仍然会被修复通过main()具有的内容,以及文件的哪些部分的数据不易预测。

此外,如果来自fillTrans()的写入仍然存在,则在已​​经写入已经刷新到磁盘的任何main()之后(如果有的话),它们将被添加到文件的末尾,因为fillTrans()以附加模式打开。

相关问题