回覆列表
  • 1 # 錢布斯

    花了我半個小時,給了寫了一個簡單的例子,以下是在vs2005下除錯成功,test.txt為檔名,在當前目錄下。

    #include <stdio.h>

    #include <stdlib.h>

    #define TRUE 1

    #define FALSE 0

    typedef struct Node

    {

    int num;

    int score;

    struct Node* next;

    }Node, *Linklist;

    void InitLinklist(Linklist* L) //初始化單鏈表,建立空的帶頭結點的連結串列

    {

    *L = (Node*)malloc(sizeof(Node));

    (*L)->next = NULL;

    }

    void CreateLinklist(Linklist L) //尾插法建立單鏈表

    {

    Node *r, *s;

    r = L;

    int iNum, iScore;

    printf("Please input the number and score:\n");

    scanf("%d",&iNum);

    scanf("%d",&iScore);

    while(0 != iScore) //當成績為負時,結束輸入

    {

    s = (Node*)malloc(sizeof(Node));

    s->num = iNum;

    s->score = iScore;

    r->next = s;

    r =s;

    printf("Please input the number and score:\n");

    scanf("%d",&iNum);

    scanf("%d",&iScore);

    }

    r->next = NULL; //將最後一個節點的指標域置為空

    }

    int WriteLinklistToFile(const char* strFile, Linklist L)

    {

    FILE *fpFile;

    Node *head = L->next;

    if(NULL == (fpFile = fopen(strFile,"w"))) //以寫的方式開啟

    {

    printf("Open file failed\n");

    return FALSE;

    }

    while(NULL != head)

    {

    fprintf(fpFile,"%d\t%d\n",head->num,head->score);

    head = head->next;

    }

    if(NULL != fpFile)

    fclose(fpFile);

    return TRUE;

    };

    int ReadFromFile(const char* strFile)

    {

    FILE *fpFile;

    if(NULL == (fpFile = fopen(strFile,"r"))) //以讀的方式開啟

    {

    printf("Open file failed\n");

    return FALSE;

    }

    printf("The contents of File are:\n");

    while(!feof(fpFile))

    putchar(fgetc(fpFile));//證明fprintf()輸出到檔案中的絕對是字串

    if(NULL != fpFile)

    fclose(fpFile);

    return TRUE;

    }

    void Destroy(Linklist L)

    {

    Node *head =L;

    while (head)

    {

    Node* temp = head;

    head = head->next;

    free(temp);

    }

    }

    int main()

    {

    char* strName = "test.txt";

    Linklist L;

    InitLinklist(&L);

    CreateLinklist(L);

    WriteLinklistToFile(strName, L);

    ReadFromFile(strName);

    Destroy(L);

    return 0;

    }

  • 中秋節和大豐收的關聯?
  • 京劇唱臉譜是用什麼唱腔來演唱?