1

我尝试使用 mygets 函数,以便 fgets 只会读取一行:

void * mygets(char *name, int len, FILE * stream)
{
    fgets(name,len,stream);

    if (name[strlen(name) - 1] == 10)
    {
        name[strlen(name) - 1] = 0;
    }
}

文件内容是:

John Smith //Name

19 // Age

175.62 // Height

87  // Weight

使用单链表,我只想*mygets读取,John Smith然后将其存储到一个名为 typedef 的结构client中:

typedef struct nodebase{
    char name[40]; //Just in case, the client's name can be long
    int age;
    double height;
    int weight;
    struct nodebase *next;
    }listnode;

int main()
{
listnode *head;
listnode *tail;
listnode *client;
FILE *f;

f=fopen("filename.txt","r");

while(!feof(filename))
{
    client = malloc(sizeof(listnode));
    mygets(client->name,40,filename);

    if (head == NULL)
    {
        head = client;
    }
    else 
    {
        tail->next=client;
    }
    tail = client;
    client =head;
}

while(client!=NULL)
{
    printf("\n%s\n",&client->name);
    client = client->next;
}

}

但问题是,程序会打印整个文件(包括年龄、身高和体重)。

我找不到我的*mygets.

***我在 Windows 上使用 Tiny C

4

1 回答 1

1

You have lots of typos and mistakes in the code you have posted in your question.

  1. FILE *f declaration doesn't end with semicolon;
  2. Condition in while(client!NULL) is not valid C condition, it should be != there;
  3. head and tail did not declared.

I hope that by the way you have working version of this code.

What is about your question, the code just works as it is written - your mygets function reads a line from the file, so in your while(!feof(filename)) loop you read file contents line by line (name, age, height, weight) and put entries into the linked-list. Then you just print them by traversing linked list from beginning to the end.

于 2013-09-25T16:22:44.073 回答