@@ -1690,6 +1690,9 @@ chsrc_append_to_file (const char *str, const char *filename)
16901690 */
16911691}
16921692
1693+ /**
1694+ * @note 本函数不会自动在 str 末尾添加换行符
1695+ */
16931696static void
16941697chsrc_prepend_to_file (const char * str , const char * filename )
16951698{
@@ -1702,16 +1705,64 @@ chsrc_prepend_to_file (const char *str, const char *filename)
17021705 char * dir = xy_parent_dir (file );
17031706 chsrc_ensure_dir (dir );
17041707
1705- char * cmd = NULL ;
1706- if (xy .on_windows )
1708+ char * tmpfile_name = "prepend" ;
1709+ char * tmpfile_ext = ".txt" ;
1710+ char * tmpnull = "" ;
1711+ FILE * tmp = chsrc_make_tmpfile (tmpfile_name , tmpfile_ext , true, & tmpnull );
1712+ fclose (tmp );
1713+ char * temp_file = xy_strcat (3 , "chsrc_tmp_" , tmpfile_name , tmpfile_ext );
1714+
1715+ FILE * input = fopen (file , "r" );
1716+ FILE * output = fopen (temp_file , "w" );
1717+
1718+ if (!output )
17071719 {
1708- xy_unimplemented ();
1720+ if (input ) fclose (input );
1721+ free (temp_file );
1722+ char * msg = ENGLISH ? xy_2strcat ("Create temp file before Write prepend failed " , file )
1723+ : xy_2strcat ("尝试在文件开头写入时创建临时文件失败:" , file );
1724+ chsrc_error2 (msg );
1725+ exit (Exit_ExternalError );
17091726 }
1710- else
1727+
1728+ // 先写入要插入的行
1729+ fprintf (output , "%s" , str );
1730+
1731+ // 如果原文件存在,复制其内容
1732+ if (input )
17111733 {
1712- cmd = xy_strcat (4 , "sed -i '1i " , str , "' " , file );
1734+ fseek (input , 0 , SEEK_END );
1735+ long file_size = ftell (input );
1736+ fseek (input , 0 , SEEK_SET );
1737+
1738+ char * buffer = malloc (file_size );
1739+ if (buffer == NULL )
1740+ {
1741+ fclose (input );
1742+ return ;
1743+ }
1744+
1745+ size_t bytes = fread (buffer , 1 , file_size , input );
1746+ if (bytes > 0 ) fwrite (buffer , 1 , bytes , output );
1747+
1748+ free (buffer );
1749+ fclose (input );
17131750 }
1714- chsrc_run_as_a_service (cmd );
1751+
1752+ fclose (output );
1753+ remove (file );
1754+
1755+ if (rename (temp_file , file ) != 0 )
1756+ {
1757+ unlink (temp_file );
1758+ free (temp_file );
1759+ char * msg = ENGLISH ? xy_2strcat ("Write prepend failed to " , file )
1760+ : xy_2strcat ("在文件开头写入失败: " , file );
1761+ chsrc_error2 (msg );
1762+ exit (Exit_ExternalError );
1763+ }
1764+
1765+ free (temp_file );
17151766
17161767log_anyway :
17171768 /* 输出recipe指定的文件名 */
0 commit comments