C language3…fig11_t5struct.c…fig11_t4struct.c

Featurd default


/*fig11_t5struct: 將資料讀出一個二進位檔(struct格式)*/

#include
#include

struct student {
       short x;
       char a[20];
       };

int main()
{
    /* Declarations */
    char name[20];
    FILE *file;
    struct student stud;    

    puts(“讀取一個二進位檔(struct格式)”);
    printf (“\n請輸入檔名 (*.dat) : “);
    scanf (“%s”, name);
    file= fopen(name, “rb”); //用wb模式開啟名稱為name的新檔,並將指針file指向該檔案的頭
    
    printf(“size = %d\n”, sizeof(struct student));

    //scanf(“%hd%s”,&stud.x, stud.a);  //注意h代表short
    fread(&stud,22,1,file);

    /* write */
    while ( !feof(file) ) {
      printf(“%hd %s\n”,stud.x,stud.a);
      fread(&stud,22,1,file);
    }

    fclose(file);
    system(“pause”);
    return 0;
 }

http://cc.shu.edu.tw/~gcsun/c97/Examples/ch11/

Tagged
Technical Project Manager (Scurm) | Programmer (C#, Vue.js) | Advocate (INFJ-A) | j172.tw 人生是朝著目標前進的長遠道路 扔掉重物 兩手空空的走會更愉快