使用fopen()函數以不一樣模式打開磁盤文件(裏面有個bug)

// openfiles.c -- 演示fopen()函數

#include <stdio.h>
#include <stdlib.h>
int main(void){
  FILE *fp;
  char ch, filename[40], mode[4];
  while(1){
    /*輸入文件名和模式*/
    puts("\nEnter a filename: ");
    gets(filename);
    puts("\nEnter a mode (max 3 characters): ");
    gets(mode);
    
    /*嘗試打開文件*/
    if((fp = fopen(filename, mode)) != NULL){
      printf("\nSuccessful opening %s in mode %s.\n", filename,mode);
      fclose(fp);
      puts("Enter x to exit, any other to continue.");
      if((ch = getc(stdin)) == 'x')
        break;
      else
        continue;
    } else {
      fprintf(stderr, "\nError opening file %s in mode %s.\n", filename, mode);
      puts("Enter x to exit, any other to try again.");
      if((ch = getc(stdin)) == 'x')
        break;
      else
        continue;
    }
  }
  return 0;
}
相關文章
相關標籤/搜索