C 庫 - tmpfile() 函式



C 庫的 FILE *tmpfile(void) 函式以二進位制更新模式 (wb+) 建立一個臨時檔案。建立的臨時檔案會在流關閉 (fclose) 或程式終止時自動刪除。

語法

以下是 C 庫 tmpfile() 函式的語法:

FILE *tmpfile(void);

引數

  • 此函式不接受任何引數。

返回值

成功時,返回一個指向新建立的臨時檔案的 FILE* 指標。失敗時,如果無法建立檔案,則返回 NULL。這可能是由於檔案描述符不足、許可權不足或臨時空間不足等原因導致的。

示例 1:建立和寫入臨時檔案

此程式建立一個臨時檔案,向其中寫入一行文字,然後讀取並列印檔案內容到標準輸出。

以下是 C 庫 tmpfile() 函式的示例。

#include <stdio.h>

int main() {
   FILE *temp = tmpfile();
   if (temp == NULL) {
       perror("Failed to create temporary file");
       return 1;
   }
   
   fprintf(temp, "This is a temporary file.\n");
   rewind(temp);
   
   char buffer[100];
   while (fgets(buffer, sizeof(buffer), temp) != NULL) {
       fputs(buffer, stdout);
   }
   
   fclose(temp);
   return 0;
}

輸出

以上程式碼產生以下結果:

This is a temporary file.

示例 2:將臨時檔案用於中間計算

此程式計算從 0 到 10 的數字的平方根,將結果寫入臨時檔案,然後讀取並列印結果。

#include <stdio.h>
#include <math.h>

int main() {
   FILE *temp = tmpfile();
   if (temp == NULL) {
       perror("Failed to create temporary file");
       return 1;
   }
   
   for (int i = 0; i <= 10; i++) {
       double value = sqrt(i);
       fprintf(temp, "%d %.2f\n", i, value);
   }
   rewind(temp);
   
   int num;
   double sqrt_value;
   while (fscanf(temp, "%d %lf", &num, &sqrt_value) != EOF) {
       printf("sqrt(%d) = %.2f\n", num, sqrt_value);
   }
   
   fclose(temp);
   return 0;
}

輸出

執行以上程式碼後,我們得到以下結果:

sqrt(0) = 0.00
sqrt(1) = 1.00
sqrt(2) = 1.41
sqrt(3) = 1.73
sqrt(4) = 2.00
sqrt(5) = 2.24
sqrt(6) = 2.45
sqrt(7) = 2.65
sqrt(8) = 2.83
sqrt(9) = 3.00
sqrt(10) = 3.16
廣告

© . All rights reserved.