#2
by かずま » 7年前
x_all と y_all は何のためにあるんですか?
分からないので、その処理は省略しました。
コード:
#include <stdio.h> // fopen, fclose, fgets, fprintf
#include <stdlib.h> // free
#include <string.h> // strdup, strtok, strcpy, strcmp
#define LINES_MAX 1000
#define WORDS_MAX 100
#define LINE_SIZE 1024
int main(void)
{
FILE *fp;
char buf[LINE_SIZE], *data1[LINES_MAX], *data2[LINES_MAX];
int n1, n2, nw1, nw2, k;
fp = fopen("in1.txt", "r");
if (!fp) return 1;
for (n1 = 0; n1 < LINES_MAX && fgets(buf, sizeof buf, fp); n1++)
data1[n1] = strdup(buf);
fclose(fp);
fp = fopen("in2.txt", "r");
if (!fp) return 2;
for (n2 = 0; n2 < LINES_MAX && fgets(buf, sizeof buf, fp); n2++)
data2[n2] = strdup(buf);
fclose(fp);
fp = fopen("out.txt", "w");
if (!fp) return 3;
for (int i = 0; i < n1; i++) {
char *line1 = data1[i], *words[WORDS_MAX], *p;
for (nw1 = 0; nw1 < WORDS_MAX && (p = strtok(line1, " \n")); line1 = NULL)
words[nw1++] = p;
if (nw1 != 3) continue;
for (int j = 0; j < n2; j++) {
char *line2 = strcpy(buf, data2[j]), *words2[WORDS_MAX];
for (nw2 = 0; nw2 < WORDS_MAX && (p = strtok(line2, " \n")); line2 = NULL)
words2[nw2++] = p;
if (nw2 != 3) continue;
for (k = 0; k < 3 && !strcmp(words[k], words2[k]); k++) ;
if (k < 3) continue;
fprintf(fp, "['%s', '%s', '%s']\n", words2[0], words2[1], words2[2]);
}
}
fclose(fp);
for (int i = 0; i < n1; i++) free(data1[i]);
for (int i = 0; i < n2; i++) free(data2[i]);
return 0;
}
行数や単語数の最大値を固定値にしています。
非標準関数の strdup を使用しています。
不都合はありますか?
x_all と y_all の処理も必要ですか?
x_all と y_all は何のためにあるんですか?
分からないので、その処理は省略しました。
[code=c]
#include <stdio.h> // fopen, fclose, fgets, fprintf
#include <stdlib.h> // free
#include <string.h> // strdup, strtok, strcpy, strcmp
#define LINES_MAX 1000
#define WORDS_MAX 100
#define LINE_SIZE 1024
int main(void)
{
FILE *fp;
char buf[LINE_SIZE], *data1[LINES_MAX], *data2[LINES_MAX];
int n1, n2, nw1, nw2, k;
fp = fopen("in1.txt", "r");
if (!fp) return 1;
for (n1 = 0; n1 < LINES_MAX && fgets(buf, sizeof buf, fp); n1++)
data1[n1] = strdup(buf);
fclose(fp);
fp = fopen("in2.txt", "r");
if (!fp) return 2;
for (n2 = 0; n2 < LINES_MAX && fgets(buf, sizeof buf, fp); n2++)
data2[n2] = strdup(buf);
fclose(fp);
fp = fopen("out.txt", "w");
if (!fp) return 3;
for (int i = 0; i < n1; i++) {
char *line1 = data1[i], *words[WORDS_MAX], *p;
for (nw1 = 0; nw1 < WORDS_MAX && (p = strtok(line1, " \n")); line1 = NULL)
words[nw1++] = p;
if (nw1 != 3) continue;
for (int j = 0; j < n2; j++) {
char *line2 = strcpy(buf, data2[j]), *words2[WORDS_MAX];
for (nw2 = 0; nw2 < WORDS_MAX && (p = strtok(line2, " \n")); line2 = NULL)
words2[nw2++] = p;
if (nw2 != 3) continue;
for (k = 0; k < 3 && !strcmp(words[k], words2[k]); k++) ;
if (k < 3) continue;
fprintf(fp, "['%s', '%s', '%s']\n", words2[0], words2[1], words2[2]);
}
}
fclose(fp);
for (int i = 0; i < n1; i++) free(data1[i]);
for (int i = 0; i < n2; i++) free(data2[i]);
return 0;
}
[/code]
行数や単語数の最大値を固定値にしています。
非標準関数の strdup を使用しています。
不都合はありますか?
x_all と y_all の処理も必要ですか?