開啟模式如下列表
| 模式 | 功能 |
|---|---|
| "r" | 讀取文字檔案 |
| "w" | 新建文字檔案並寫入資料 |
| "a" | 將資料附加在該文字檔案之後 |
| "rb" | 讀取二進位檔 |
| "wb" | 新建二進位檔並寫入資料 |
| "ab" | 將資料附加在該二進位檔之後 |
| "r+" | 讀取文字檔案並寫入資料 |
| "w+" | 新建文字檔案並讀取、寫入資料 |
| "a+" | 讀取文字檔案將附加資料在檔案最後 |
| "rb+" 或 "r+b" | 讀取二進位檔並寫入資料 |
| "wb+" 或 "w+b" | 新建二進位檔並讀取、寫入資料 |
| "ab+" 或 "a+b" | 讀取二進位檔將附加資料在檔案最後 |
以下程式嘗試讀取不存在的檔案
#include <stdio.h>
int main(void)
{
FILE *fPtr;
fPtr = fopen("oldname.txt", "r");
if (fPtr) {
printf("檔案開啟成功...\n");
fclose(fPtr);
}
else {
printf("檔案開啟失敗...\n");
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:cfopen1.c
功能:示範 stdio.h 中函數 fopen() 的使用
作者:張凱慶
時間:西元2010年6月 */編譯後執行,結果如下

以下程式建立新的檔案
#include <stdio.h>
int main(void)
{
FILE *fPtr;
fPtr = fopen("oldname.txt", "w");
if (fPtr) {
printf("檔案建立成功...\n");
fclose(fPtr);
}
else {
printf("檔案建立失敗...\n");
}
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:cfopen2.c
功能:示範 stdio.h 中函數 fopen() 的使用
作者:張凱慶
時間:西元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);
沒有留言:
張貼留言