以下程式示範用 fwrite() 寫入資料到檔案,然後用 fread() 的程式印出結果
#include <stdio.h> #include <stdlib.h> struct addressList { char nickname[30]; int age; int sex; char relation[30]; }; int main(void) { FILE *fPtr; struct addressList blankEntry1 = {"John", 15, 1, "friend"}; struct addressList blankEntry2 = {"Mary", 13, 0, "teacher"}; struct addressList blankEntry3 = {"Tony", 12, 1, "family"}; struct addressList blankEntry4 = {"Park", 14, 1, "friend"}; struct addressList blankEntry5 = {"Lily", 10, 0, "friend"}; fPtr = fopen("address.dat", "wb+"); if (!fPtr) { printf("檔案開啟失敗...\n"); exit(1); } fwrite(&blankEntry1, sizeof(struct addressList), 1, fPtr); fwrite(&blankEntry2, sizeof(struct addressList), 1, fPtr); fwrite(&blankEntry3, sizeof(struct addressList), 1, fPtr); fwrite(&blankEntry4, sizeof(struct addressList), 1, fPtr); fwrite(&blankEntry5, sizeof(struct addressList), 1, fPtr); fclose(fPtr); return 0; } /* 《程式語言教學誌》的範例程式 http://pydoing.blogspot.com/ 檔名:cfwrite.c 功能:示範 stdio.h 中函數 fwrite() 的使用 作者:張凱慶 時間:西元2010年6月 */
編譯後執行,結果如下
您可以繼續參考
輸出與輸入 stdio.h
- int getchar(void);
- char *gets(char *s);
- int putchar(int c);
- int puts(const char *s);
- int printf(const char *format, ...);
- int sprintf(char *s, const char *format, ...);
- int scanf(const char *format, ...);
- int sscanf(char *s, const char *format, ...);
- FILE *fopen(const char *filename, const char *mode);
- FILE *freopen(const char *filename, const char *mode, FILE *stream);
- int fflush(FILE *stream);
- int fclose(FILE *stream);
- int remove(const char *filename);
- int rename(const char *oldname, const char *newname);
- int fprintf(FILE *stream, const char *format, ...);
- int fscanf(FILE *stream, const char *format, ...);
- int fgetc(FILE *stream);
- char *fgets(char *s, int n, FILE *stream);
- int fputs(const char *s, FILE *stream);
- int fputs(const char *s, FILE *stream);
- size_t fread(void *ptr, size_t size, siz_t nobj, FILE *stream)
- size_t fwrite(const void *ptr, size_t size, size_t nobj, FILE *stream)
- int fseek(FILE *stream, long offset, int origin);
- long ftell(FILE *stream);
- void rewind(FILE *stream);
1 則留言:
想請問一下站長大大
為什麼最後一組的data
會重複地被show出來呢
如上述範例之Lily?
張貼留言