从c中的文件中逐字逐句保存

时间:2016-01-11 19:45:15

标签: c file

假设我们在文件中有一些联系人,比如小型电话簿。

我想创建一个类似于在线电话簿的小程序,文本中的每个联系人都需要Line的大小,并且信息的放置顺序如下:NAME SURNAME ADRESS PHONE , 但每个联系人的电话数量可能超过一个。 例如:

 George Mikels "green str" 123123 12121232 
 Maria Luis "olive str" 6548845

在我的尝试中,到目前为止我已经这样做了:

void Createtree(node **head_node)
{
    int count=0,*phones;
    char filename[50], name[30], surname[50], adress[70];
    char c;

    FILE *fp;
    printf("PLease enter the name of the file\n");
    scanf("%s", &filename);

    fp = fopen("text.txt", "r");
    if(fp == NULL)
    {
        printf("failed to open file");
        return ;
    }

    do
    {
        c=fscanf(fp, "%s %s %s ", &name, &surname, &adress);

        //takes the name ,surname and adress
        printf(" %s %s %s\n", &name, &surname, &adress);
        phones = (int*)malloc(sizeof(int));

        //creates a dynamic array of int in order to save the phones
        do
        {
            //saves each Number inside the array
            c = fscanf(fp, " %d ", phones[count]);
            count = count + 1;

            phones = (int*)realloc(phones, (count +1) * sizeof(int));

            // increases the size of the array in order to save all the phones 
        }while(c != '\n');

        //does it until the end of the Line 
        count=0;

        Insert(head_node,name,surname,phones);
        //uses a function to add the Information to a list 

    }while(c != EOF);
};

我无法将手机保存在阵列中,我不知道为什么。

1 个答案:

答案 0 :(得分:0)

尝试在读取之前分配数组,然后实际读取将初始化数组的元素。

// define max number size
int maxSizeOfNumber = 20;

// allocate dynamic memory
int *phones = malloc(maxSizeOfNumber * sizeof(int));

// read phone number
do {

    c = fscanf(fp, "%d", &phones[count]);
    count++;

} while (c > 0 && count < maxSizeOfNumber );

我建议您将电话号码存储在字符数组或字符串中,以避免存储在int中的数字,例如以0开头的数字,如由@Bob__评论部分。