解釋 C 語言錯誤處理函式


檔案是記錄的集合,或者說是硬碟上永久儲存資料的地方。

檔案操作

C 程式語言中的檔案操作如下:

  • 命名檔案
  • 開啟檔案
  • 從檔案讀取
  • 寫入檔案
  • 關閉檔案

語法

開啟檔案的語法如下:

FILE *File pointer;

例如,FILE * fptr;

命名檔案的語法如下:

File pointer = fopen ("File name", "mode");

例如,

fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");

檔案錯誤處理

一些檔案錯誤如下:

  • 嘗試讀取檔案末尾之外的內容。
  • 裝置溢位。
  • 嘗試開啟無效檔案。
  • 透過以不同的模式開啟檔案來執行無效操作。

ferror( )

它用於檢測在執行讀/寫操作時發生的錯誤。

ferror() 函式的語法如下:

語法

int ferror (file pointer);

例如,

示例

FILE *fp;
if (ferror (fp))
printf ("error has occurred");

如果成功,則返回零,否則返回非零值。

程式

以下是使用 ferror() 函式的 C 程式:

#include<stdio.h>
int main(){
   FILE *fptr;
   fptr = fopen("sample.txt","r");
   if(ferror(fptr)!=0)
      printf("error occurred");
   putc('T',fptr);
   if(ferror(fptr)!=0)
      printf("error occurred");
   fclose(fptr);
   return 0;
}

輸出

執行上述程式時,會產生以下結果:

error occurred
Note: try to write a file in the read mode results an error.

perror ( )

它用於列印錯誤。

perror() 函式的語法如下:

語法

perror (string variable);

例如,

示例

FILE *fp;
char str[30] = "Error is";
perror (str);

輸出如下:

Error is: error 0

程式

以下是使用 perror() 函式的 C 程式:

#include<stdio.h>
int main ( ){
   FILE *fp;
   char str[30] = "error is";
   int i = 20;
   fp = fopen ("sample.txt", "r");
   if (fp == NULL){
      printf ("file doesnot exist");
   }
   else{
      fprintf (fp, "%d", i);
      if (ferror (fp)){
         perror (str);
         printf ("error since file is opened for reading only");
      }
   }
   fclose (fp);
   return 0;
}

輸出

執行上述程式時,會產生以下結果:

error is: Bad file descriptor
error since file is opened for reading only

feof( )

它用於檢查是否已到達檔案末尾。

feof() 函式的語法如下:

語法

int feof (file pointer);

例如,

示例

FILE *fp;
if (feof (fp))
printf ("reached end of the file");

如果成功,則返回非零值,否則返回零。

程式

以下是使用 feof() 函式的 C 程式:

即時演示

#include<stdio.h>
main ( ){
   FILE *fp;
   int i,n;
   fp = fopen ("number. txt", "w");
   for (i=0; i<=100;i= i+10){
      putw (i, fp);
   }
   fclose (fp);
   fp = fopen ("number. txt", "r");
   printf ("file content is");
   for (i=0; i<=100; i++){
      n = getw (fp);
      if (feof (fp)){
         printf ("reached end of file");
         break;
      }else{
         printf ("%d", n);
      }
   }
   fclose (fp);
   getch ( );
}

輸出

執行上述程式時,會產生以下結果:

File content is
10 20 30 40 50
60 70 80 90 100
Reached end of the file.

更新於: 2021-03-24

717 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告