在C中的文件中添加结构数组

时间:2019-03-13 15:40:17

标签: c arrays file struct

我有一个代码,可以在其中将struct数组添加到文件中,但是无法像我本应的那样继续将联系人添加到struct数组中。

这是我的变量:

struct contact {                // Data structure that holds contact information 
    char FirstName[10];         // Array for first name
    char LastName[10];          // Array for last name
    int PhoneNum;               // Phone number
};

int Choice = 0;
    int n = 0;
    int size = 1;
    struct contact *con = (struct contact *)malloc(size * sizeof(struct contact));
    int a = 0;
    int b = 0;
    int SortChoice = 0;
    int iRandNum = 0;
    int Valid = 0;
    char temp[10];
    int tempNum = 0;
    char File[20];
    int status = 0;

    FILE *pRead;
    FILE *pWrite;

这是添加联系人部分:

if (n == size)
            {
                size = size * 2;
                con = (struct contact*)realloc(con, size * sizeof(struct contact));
            }
            // Records the information given into the structure
            printf("\nYou chose to add a contact.");
            printf("\nFirst name: ");
            scanf("%s", con[n].FirstName);
            printf("\nLast name: ");
            scanf("%s", con[n].LastName);
            printf("\nPhone number (Numbers only): ");
            scanf("%d", &con[n].PhoneNum);
            printf("\nRecord added to the phone book.");

            // Prints out the given information
            printf("\n\nNew contact:");
            printf("\nFirst name: %s", con[n].FirstName);
            printf("\nLast name: %s", con[n].LastName);
            printf("\nPhone number: %d", con[n].PhoneNum);
            printf("\nContact number is %d", n);
            printf("\n");
            n += 1;

这是文件部分:

printf("\nYou chose to store all contacts to a file.");

            if (status == 0){
                printf("\nWhat would you like to name your file?\n");
                scanf("%s", &File);
                printf("\nFile name is %s", File);
                pWrite = fopen(File, "w");

                if (pWrite == 0){
                    printf("\nFile not opened");
                }
                else {
                    for (a = 0; a < n; a++){
                        fwrite(&con[a], sizeof(struct contact), 1, pWrite);
                    }
                    fclose(pWrite);
                    pRead =fopen(File, "r");
                    printf("\n\nContacts added to %s", File);
                    printf("\n\nContacts in file:\n");
                    while (fread(&con[a], sizeof(struct contact),1, pRead)){
                        printf("\n");
                        printf("\nFirst name: %s", con[a].FirstName);
                        printf("\nLast name: %s", con[a].LastName);
                        printf("\nPhone number: %d", con[a].PhoneNum);
                        printf("\n");
                    }
                    fclose(pRead);
                }
            }

如果你们能弄清楚我哪里出了问题,以及潜在的原因为什么我不能继续访问我创建的文件,那将是很棒的。谢谢

0 个答案:

没有答案