Add chsrc_make_tmpfile()

This commit is contained in:
Aoran Zeng 2025-07-14 20:40:48 +08:00
parent 5c85073939
commit 0b5c67811e
No known key found for this signature in database
GPG Key ID: 8F8BA8488E10ED98

View File

@ -1308,6 +1308,74 @@ chsrc_run_as_a_service (const char *cmd)
ProgStatus.chsrc_run_faas = false;
}
/**
* @brief
*
* @param[in] filename
* @oaram[in] postfix '.'
* @oaram[in] loud
* @param[out] tmpfilename NULL
*
* @return FILE*
*/
FILE *
chsrc_make_tmpfile (char *filename, char *postfix, bool loud, char **tmpfilename)
{
#ifdef XY_On_Windows
/**
* Windows mkstemps() mkstemp() _mktemp_s()
* postfix
* PowerShell 使 -File .ps1
* 使 Windows
*/
char *tmpfile = xy_strjoin (3, "chsrc_tmp_", filename, postfix);
FILE *f = fopen (tmpfile, "w+");
#else
char *tmpfile = xy_strjoin (4, "/tmp/", "chsrc_tmp_", filename, "_XXXXXX", postfix);
size_t postfix_len = strlen (postfix);
/* 和 _mktemp_s() 参数不同,前者是整个缓存区大小,这里的长度是后缀长度 */
int fd = mkstemps (tmpfile, postfix_len);
FILE *f = fdopen (fd, "w+");
#endif
if (!f)
{
char *msg = CHINESE ? "无法创建临时文件: " : "Unable to create temporary file: ";
msg = xy_2strjoin (msg, tmpfile);
chsrc_error2 (msg);
exit (Exit_ExternalError);
}
else if (loud)
{
char *msg = CHINESE ? "已创建临时文件: " : "Temporary file created: ";
msg = xy_2strjoin (msg, tmpfile);
chsrc_succ2 (msg);
}
/**
* FILE*
* /tmp
* Windows Windows
*/
if (xy_on_windows && !tmpfilename)
{
chsrc_error2 ("在 Windows 上,创建临时文件时必须指定返回的临时文件名");
xy_unreached();
}
if (tmpfilename)
{
*tmpfilename = xy_strdup (tmpfile);
}
return f;
}
static void
chsrc_view_env (const char *var1, ...)
{