简体   繁体   English

从每一行,从c中的文件中逐字保存

[英]saving word by word ,from each line , from a file in c

Suppose we have some contacts in a file, like a small phone book. 假设我们在文件中有一些联系人,例如一本小电话簿。

I want to make a small programme that works like an online phone book each contact in the text takes the size of a Line and, the order that the Information is placed looks like this : NAME SURNAME ADRESS PHONE , but the Number of phones that each contact has can be more then one. 我想制作一个像在线电话簿一样工作的小程序,文本中的每个联系人都占用Line的大小,并且信息的放置顺序如下: NAME SURNAME ADRESS PHONE ,但是每个电话的数量接触可以超过一个。 so for example : 因此,例如:

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

In my attempt I have done this so far: 到目前为止,我已经尝试过:

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);
};

I can't save the phones inside the array and I don't know why. 我无法将手机保存在阵列中,也不知道为什么。

Try allocating the array before the reading and then the actual reading would initialize array's elements. 尝试在读取之前分配数组,然后实际读取将初始化数组的元素。

// 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 );

I would advice you to store phone numbers either in character array or string to avoid numbers that would not be stored in an int , for example those starting with 0 's, as mentioned in the comment section by @Bob__. 我建议您将电话号码存储在字符数组或字符串中,以避免将数字存储在int ,例如,以0开头的数字,如@Bob__的注释部分所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM