File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -610,6 +610,59 @@ xy_str_strip (const char *str)
610610}
611611
612612
613+ /**
614+ * @brief 读取文件内容并返回字符串,失败时返回空字符串
615+ * @note 已处理 `\r\n` 和 `\r`,返回的字符串均为 `\n` 换行
616+ */
617+ static char *
618+ xy_file_to_str (const char * path )
619+ {
620+ FILE * fp = fopen (path , "rb" );
621+ if (!fp )
622+ return xy_strdup ("" );
623+
624+ if (fseek (fp , 0 , SEEK_END ) != 0 )
625+ {
626+ fclose (fp );
627+ return xy_strdup ("" );
628+ }
629+
630+ long size = ftell (fp );
631+ if (size < 0 )
632+ {
633+ fclose (fp );
634+ return xy_strdup ("" );
635+ }
636+ rewind (fp );
637+
638+ char * buf = xy_malloc0 ((size_t ) size + 1 );
639+ if (!buf )
640+ {
641+ fclose (fp );
642+ return xy_strdup ("" );
643+ }
644+
645+ size_t read_bytes = fread (buf , 1 , (size_t ) size , fp );
646+ if (read_bytes < (size_t ) size && ferror (fp ))
647+ {
648+ fclose (fp );
649+ free (buf );
650+ return xy_strdup ("" );
651+ }
652+
653+ fclose (fp );
654+ buf [read_bytes ] = '\0' ;
655+
656+ char * formatted_str = xy_str_gsub (buf , "\r\n" , "\n" );
657+ formatted_str = xy_str_gsub (formatted_str , "\r" , "\n" );
658+
659+ free (buf );
660+
661+ return formatted_str ;
662+ }
663+
664+
665+
613666/******************************************************
614667 * Logging
615668 ******************************************************/
You can’t perform that action at this time.
0 commit comments