以下程序实现将一个中文字幕和一个英文字幕合并成一个中英字幕。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SUBFORM ".srt*"
long FileRow(char *filepath) /*读取文件行数*/
{
FILE *fp;
long row_count = 0;
char c;
if((fp = fopen(filepath, "r")) == NULL)
{
perror("Can't open!");
exit(1);
}
while(!feof(fp))
{
if(c = fgetc(fp) == '\n')
row_count++;
}
fclose(fp);
return row_count;
}
void chs_eng(char *filepath_eng, char *filepath_chs)
{
char **engsub; /*按时间段存取所有英文字幕*/
char *chs_time_buf; /*存取每一行的中文时间*/
char *chs_str_buf; /*存取每一行的中文字幕*/
FILE *fp_eng, *fp_chs, *fp_new;
char *buf; /*每一行数据缓存*/
char *filepath_new;
int index = 0, englen = 0;
long row_count = 0;
if((fp_eng = fopen(filepath_eng, "r")) == NULL)
{
perror("Faile to popen\n");
exit(1);
}
if((fp_chs = fopen(filepath_chs, "r")) == NULL)
{
perror("Faile to popen\n");
exit(1);
}
filepath_new = (char *)calloc(strlen(filepath_chs) + 5, sizeof(char));
strcpy(filepath_new, filepath_chs);
strcat(filepath_new, "*");
if(strstr(filepath_new, SUBFORM) == false)
{
perror("Subfile type wrong!");
exit(1);
}
*strstr(filepath_new, SUBFORM) = '\0';
strcat(filepath_new, "_eng");
strcat(filepath_new, SUBFORM);
*(filepath_new + strlen(filepath_new) - 1) = '\0';
if((fp_new = fopen(filepath_new, "wb+")) == NULL)
{
perror("Faile to popen\n");
exit(1);
}
if(FileRow(filepath_eng) > FileRow(filepath_chs)) row_count = FileRow(filepath_eng);
else row_count = FileRow(filepath_chs);
engsub = (char **)calloc(row_count / 3, sizeof(char *));
chs_time_buf = (char *)calloc(128, sizeof(char));
chs_str_buf = (char *)calloc(128, sizeof(char));
buf = (char *)calloc(128, sizeof(char));
while(!feof(fp_eng)) /*遍历英文字幕文件,存取数据*/
{
fgets(buf, 128, fp_eng);
if(strstr(buf, "-->") != NULL)
{
engsub[index] = (char *)calloc(128, sizeof(char));
while(!feof(fp_eng))
{
fgets(buf, 128, fp_eng);
if(strcmp(buf, "\n") == 0) break;
strcat(engsub[index], buf);
}
index++;
}
}
englen = index;
index = 0;
while(!feof(fp_chs) && index < englen) /*遍历中文字幕文件,存取数据*/
{
fgets(buf, 128, fp_chs);
if(strstr(buf, "-->") != NULL)
{
if(index > 0 && strcmp(buf, chs_time_buf) == 0) continue;
strcpy(chs_time_buf, buf);
strcpy(chs_str_buf, "");
while(!feof(fp_chs) && index < englen)
{
fgets(buf, 128, fp_chs);
if(strcmp(buf, "\n") == 0)
{
strcat(chs_str_buf, engsub[index]); /*如果遇到空行,添加英文字幕*/
break;
}
strcat(chs_str_buf, buf);
}
if(strstr(chs_str_buf, "{")) continue;
fprintf(fp_new, "%d\n", index + 1);
fputs(chs_time_buf, fp_new);
fputs(chs_str_buf, fp_new);
fputs("\n", fp_new);
index++;
}
}
for(index = 0; index < englen; index++)
free(engsub[index]);
free(engsub);
free(filepath_new);
free(chs_time_buf);
free(chs_str_buf);
free(buf);
fclose(fp_chs);
fclose(fp_eng);
fclose(fp_new);
}
int main()
{
char *filepath_eng = "D:\\文档\\CB\\sub\\subfile\\Elementary.S02E24.720p.HDTV.X264-DIMENSION.英文.srt";
char *filepath_chs = "D:\\文档\\CB\\sub\\subfile\\Elementary.S02E24.720p.HDTV.X264-DIMENSION.简体.srt";
chs_eng(filepath_eng, filepath_chs);
return 0;
}