@@ -1308,6 +1308,74 @@ chsrc_run_as_a_service (const char *cmd)
13081308 ProgStatus .chsrc_run_faas = false;
13091309}
13101310
1311+
1312+
1313+ /**
1314+ * @brief 在本目录创建一个临时文件
1315+ *
1316+ * @param[in] filename 文件名,不包含后缀名
1317+ * @oaram[in] postfix 后缀名,需要自己加 '.'
1318+ * @oaram[in] loud 创建成功时是否提示用户
1319+ * @param[out] tmpfilename 生成的临时文件名,可以为 NULL
1320+ *
1321+ * @return 返回一个 FILE*,调用者需要关闭该文件
1322+ */
1323+ FILE *
1324+ chsrc_make_tmpfile (char * filename , char * postfix , bool loud , char * * tmpfilename )
1325+ {
1326+ #ifdef XY_On_Windows
1327+ /**
1328+ * Windows 上没有 mkstemps(),只有 mkstemp() 和 _mktemp_s(),这后两者效果是等价的,只不过传参不同,
1329+ * 这意味着我们无法给一个文件名后缀(postfix),只能生成一个临时文件名
1330+ * 然而 PowerShell 的执行,即使加了 -File 参数,也必须要求你拥有 .ps1 后缀
1331+ * 这使得我们在 Windows 上只能创建一个假的临时文件
1332+ */
1333+ char * tmpfile = xy_strjoin (3 , "chsrc_tmp_" , filename , postfix );
1334+ FILE * f = fopen (tmpfile , "w+" );
1335+ #else
1336+ char * tmpfile = xy_strjoin (4 , "/tmp/" , "chsrc_tmp_" , filename , "_XXXXXX" , postfix );
1337+ size_t postfix_len = strlen (postfix );
1338+
1339+ /* 和 _mktemp_s() 参数不同,前者是整个缓存区大小,这里的长度是后缀长度 */
1340+ int fd = mkstemps (tmpfile , postfix_len );
1341+ FILE * f = fdopen (fd , "w+" );
1342+ #endif
1343+
1344+ if (!f )
1345+ {
1346+ char * msg = CHINESE ? "无法创建临时文件: " : "Unable to create temporary file: " ;
1347+ msg = xy_2strjoin (msg , tmpfile );
1348+ chsrc_error2 (msg );
1349+ exit (Exit_ExternalError );
1350+ }
1351+ else if (loud )
1352+ {
1353+ char * msg = CHINESE ? "已创建临时文件: " : "Temporary file created: " ;
1354+ msg = xy_2strjoin (msg , tmpfile );
1355+ chsrc_succ2 (msg );
1356+ }
1357+
1358+ /**
1359+ * 允许生成文件后不了解其文件名,调用者只了解 FILE*
1360+ * 这样的话,其实是是无法删除该文件的,但是生成在 /tmp 目录下我们恰好可以不用清理
1361+ * 但是在 Windows 上,就没有办法了,所以我们禁止在 Windows 上不指定返回出的临时文件名
1362+ */
1363+ if (xy_on_windows && !tmpfilename )
1364+ {
1365+ chsrc_error2 ("在 Windows 上,创建临时文件时必须指定返回的临时文件名" );
1366+ xy_unreached ();
1367+ }
1368+
1369+ if (tmpfilename )
1370+ {
1371+ * tmpfilename = xy_strdup (tmpfile );
1372+ }
1373+
1374+ return f ;
1375+ }
1376+
1377+
1378+
13111379static void
13121380chsrc_view_env (const char * var1 , ...)
13131381{
0 commit comments