名稱空間
變體
操作

tmpnam, tmpnam_s

來自 cppreference.com
< c‎ | io
 
 
檔案輸入/輸出
型別和物件
        
函式
檔案訪問
(C95)
非格式化輸入/輸出
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)

格式化輸入
直接輸入/輸出
格式化輸出
檔案定位
錯誤處理
檔案操作
tmpnamtmpnam_s
(C11)
 
定義於標頭檔案 <stdio.h>
char *tmpnam( char *filename );
(1)
errno_t tmpnam_s(char *filename_s, rsize_t maxsize);
(2) (C11 起)
#define TMP_MAX        /*未指定*/
#define TMP_MAX_S      /*未指定*/
(C11 起)
#define L_tmpnam       /*未指定*/
#define L_tmpnam_s     /*未指定*/
(C11 起)
1) 建立一個唯一有效的臨時檔名(長度不超過 L_tmpnam),並將其儲存在 filename 指向的字元字串中。此函式能夠生成多達 TMP_MAX 個唯一檔名,但其中部分或全部可能已被檔案系統使用,因此不適合作為返回值。
2) 功能與 (1) 相同,但可以生成多達 TMP_MAX_S 個名稱,長度不超過 L_tmpnam_s。此外,在執行時會檢測以下錯誤並呼叫當前已安裝的 約束處理函式
  • filename_s 是空指標
  • maxsize 大於 RSIZE_MAX
  • maxsize 小於生成的檔名字串長度
與所有邊界檢查函式一樣,tmpnam_s 僅在實現定義了 __STDC_LIB_EXT1__ 且使用者在包含 <stdio.h> 之前將 __STDC_WANT_LIB_EXT1__ 定義為整數常量 1 時才保證可用。

tmpnamtmpnam_s 會修改靜態狀態(可能在這些函式之間共享),並且不要求是執行緒安全的。

目錄

[編輯] 引數

filename - 指向字元陣列的指標,該陣列至少能容納 L_tmpnam 位元組,用作結果緩衝區。如果傳入空指標,則返回指向內部靜態緩衝區的指標。
filename_s - 指向字元陣列的指標,該陣列至少能容納 L_tmpnam_s 位元組,用作結果緩衝區。
maxsize - 函式允許寫入的最大字元數(通常是 filename_s 陣列的大小)。

[編輯] 返回值

1) 如果 filename 不是空指標,則返回 filename。否則,返回指向內部靜態緩衝區的指標。如果無法生成合適的檔名,則返回空指標。
2) 成功時返回零,並將檔名寫入 filename_s。出錯時返回非零值,並將空字元寫入 filename_s[0](僅當 filename_s 非空且 maxsize 非零且不大於 RSIZE_MAX 時)。

[編輯] 注意

儘管 tmpnam 生成的名稱難以猜測,但在 tmpnam 返回和程式嘗試使用返回的名稱建立檔案之間,仍可能存在另一個程序建立同名檔案的情況。標準函式 tmpfile 和 POSIX 函式 mkstemp 沒有此問題(僅使用標準 C 庫建立唯一目錄仍然需要使用 tmpnam)。

POSIX 系統還定義了類似的函式 tempnam,它允許選擇目錄(預設為可選定義的宏 P_tmpdir)。

[編輯] 示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void)
{
    // Note, the compiler/linker may issue a security warning, e.g. GCC:
    // "warning: the use of `tmpnam' is dangerous, better use `mkstemp'"
    char* name1 = tmpnam(NULL);
    printf("temporary file name: %s\n", name1);
 
    char name2[L_tmpnam];
    if (tmpnam(name2))
        printf("temporary file name: %s\n", name2);
 
    // POSIX offers mkstemp. The following declaration might be
    // necessary as mkstemp is absent in the standard C <stdlib.h>.
    int mkstemp(char*);
 
    char name3[] = "/tmp/fileXXXXXX"; // at least six 'X' required ^_^
    int file_descriptor = mkstemp(name3);
    if (file_descriptor != -1)
        printf("temporary file name: %s\n", name3);
    else
        perror("mkstemp");
}

可能的輸出

temporary file name: /tmp/file90dLlR
temporary file name: /tmp/fileY9LWAg
temporary file name: /tmp/filexgv8PF

[編輯] 參考資料

  • C23 標準 (ISO/IEC 9899:2024)
  • 7.21.4.4 tmpnam 函式 (p: TBD)
  • K.3.5.1.2 tmpnam_s 函式 (p: TBD)
  • C17 標準 (ISO/IEC 9899:2018)
  • 7.21.4.4 tmpnam 函式 (p: 222)
  • K.3.5.1.2 tmpnam_s 函式 (p: 427-428)
  • C11 標準 (ISO/IEC 9899:2011)
  • 7.21.4.4 tmpnam 函式 (p: 303-304)
  • K.3.5.1.2 tmpnam_s 函式 (p: 587-588)
  • C99 標準 (ISO/IEC 9899:1999)
  • 7.19.4.4 tmpnam 函式 (p: 269-270)
  • C89/C90 標準 (ISO/IEC 9899:1990)
  • 4.9.4.4 tmpnam 函式

[編輯] 參閱

返回指向臨時檔案的指標
(函式) [編輯]
C++ 文件 關於 tmpnam