コード:
#include <stdio.h> // fopen, fclose, fgets, printf, sscanf, sprintf, remove, tmpnam
#include <stdlib.h> // system
#include <string.h> // strstr, strchr, memcpy, memmove
#define N 256
void find_line(int);
void strchg(char *, const char *, const char *);
char *filename = "readme.txt";
char tempname[256];
char buf[1024*1024];
int main(void)
{
char readline[N];
FILE *fp = fopen(filename, "r");
if (!fp) return fprintf(stderr, "can't open %s\n", filename), 1;
tmpnam(tempname);
if (system("ping translate.google.co.jp>nul"))
return printf("通信エラー:Google 翻訳に接続できません。\n"), 1;
while (fgets(readline, N, fp)) {
int nspace;
char word[N + 100], cmd[N + 300], *p = word, *q = readline, c;
while (*q == ' ') q++;
nspace = q - readline;
while ((c = *q++) != '\0' && c != '\n')
if (strchr(" \"#&+", c)) p += sprintf(p, "%%%02X", c);
else *p++ = c;
*p = '\0';
if (*word) {
sprintf(cmd, "powershell -command wget \"\"\"https:"
"//translate.google.co.jp/?oe=cp932&text=%s\"\"\""
" -outfile '%s'", word, tempname);
system(cmd);
find_line(nspace);
}
else putchar('\n');
}
fclose(fp);
remove(tempname);
return 0;
}
void find_line(int nspace)
{
FILE *fp = fopen(tempname, "r");
if (!fp) return;
while (fgets(buf, sizeof buf, fp)) {
char *p = strstr(buf, "<span id=result_box");
if (p) {
p = strchr(strchr(p, '>') + 1, '>') + 1;
*strchr(p, '<') = '\0';
strchg(p,"&", "&");
strchg(p,""", "\"");
strchg(p,"'", "'");
strchg(p," ", " ");
strchg(p,"&", "&");
strchg(p,"#", "#");
printf("%*s%s\n", nspace, "", p);
}
}
fclose(fp);
}
void strchg(char *buf, const char *str1, const char *str2)
{
char *p = strstr(buf, str1);
if (p) {
int len = strlen(p) + 1, len1 = strlen(str1), len2 = strlen(str2);
do {
len -= p - buf + len1;
buf = p + len2;
memmove(buf, p + len1, len);
memcpy(p, str2, len2);
} while ((p = strstr(buf, str1)) != NULL);
}
}