我试图使用fgets访问下一行以计算与下一行类似的行数,无论如何都要获取nextLine变量吗?
int similar = 0;
char line[100];
char nextLine[100];
FILE *f = fopen(file, "r");
while (fgets(line, 100, f)) {
if (strcmp(nextLine, line) == '0') {
similar++;
}
}

答案 0 :(得分:2)
可以 - 添加一个新的var next_line
。例如,
int similar = 0;
char line[100] = "";
char next_line[100] = "";
FILE *f = fopen(file, "r");
while (fgets(line, 100, f)) {
if (strcmp(next_line, line) == 0) {
similar++;
}
strcpy(next_line, line);
}
注:
strcmp
检查0
,而不是'0'
答案 1 :(得分:0)
将当前行与前一行比较或将当前行与定义的字符串进行比较:
防爆。我的文本文件包含以下文本:
This is a line // (\n)
This is a line // (\n)
This is a line // without newline
char line_comp [] = "This is a line\n"; // For lines with newline
char line_comp2 [] = "This is a line"; // For lines without newline
char line[255]; // Store the line
现在我们可以查看文件,看看这些行是否符合上述条件之一:
int equal = 0;
while (fgets(line, 255, f) != NULL) {
if (strcmp(line, line_comp) == 0 || strcmp(line, line_comp2) == 0)
++equal;
}
然后最后打印结果:printf("Lines equal: %d\n", equal);
请记住检查文件是否正确打开,并记得在使用后关闭文件。