1. 要求:
有原始歌詞文件“xxx.lrc”,通過編寫程序生成新的文件“完整歌詞.txt”,內容應與正常播放順序一致。
2. 代碼:
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string.h>
#include <string>
#include <algorithm>
#define MAXLINE 256
using namespace std;
typedef struct Number {
int time;//歌詞時間
int line;//所在行
};
static int LINE = 0;//記錄歌詞所在的行
int LRCPrase(char *str, vector<string> &sentences, vector<Number> &songTime);
int strtoint(char *str);
int operator<(Number x, Number y);
int main(int argc, char *argv[]) {
char buf[MAXLINE];
vector<string> sentences, finalSentence;
vector<Number> songTime;
FILE *fd1, *fd2;
fd1 = fopen("C:\\Users\\Lenovo\\Desktop\\七里香.lrc", "r");
fd2 = fopen("C:\\Users\\Lenovo\\Desktop\\完整歌詞.txt", "w");
if (fd1 == NULL) {
perror("open file");
exit(1);
}
//處理歌詞
while (fgets(buf, sizeof(buf), fd1) != NULL) {
LRCPrase(buf, sentences, songTime);
}
sort(songTime.begin(), songTime.end());
//按照時間排序
vector<Number>::iterator it1 = songTime.begin();
for (; it1 != songTime.end(); it1++) {
finalSentence.push_back(sentences[(*it1).line]);
}
//寫入指定的文件中
it1 = songTime.begin();
vector<string>::iterator it = finalSentence.begin();
for (; it1 != songTime.end() && it != finalSentence.end(); it1++, it++) {
fputs((*it).c_str(),fd2);
}
return 0;
}
int LRCPrase(char *str, vector<string> &sentences, vector<Number> &songTime) {
if (strlen(str) == 1) {//空行
return 0;
}
else {
char *p, *q, *temp = NULL;
q = str;
//處理時間
while ((p = strchr(q, '[')) != NULL && (temp = strchr(q, ']')) != NULL) {
q = p + 1;
q[temp - q] = '\0';
struct Number number;
if ((number.time = strtoint(q)) < 0) {
return 0;
}
number.line = LINE;
songTime.push_back(number);
q = temp + 1;
}
p = ++temp;
while (*temp != NULL) {
temp++;
}
p[temp - p] = '\0';
string s(p);
sentences.push_back(s);
LINE++;
return 1;
}
}
//把char轉換爲int
int chartoint(char ch) {
return ch - '0';
}
int strtoint(char *str) {//計算時間,微秒
if (isdigit(str[0]) && isdigit(str[1])
&& isdigit(str[0]) && isdigit(str[0])
&& isdigit(str[0]) && isdigit(str[0])) {
int mintue = chartoint(str[0]) * 10 + chartoint(str[1]);
int second = chartoint(str[3]) * 10 + chartoint(str[4]);
int microsecond = chartoint(str[6]) * 10 + chartoint(str[7]);
return (mintue * 60 + second) * 1000 + microsecond * 10;
}
return -1;
}
//重載<操作符,用在sort函數比較中
int operator<(Number x, Number y) {
return x.time < y.time;
}
3. 運行結果:
處理前文件:
處理後文件: