我在运行代码时收到段错误(核心转储)错误。在使用一些 printf 语句后,我发现 strcmp 部分有错误,可能是因为将 char 与 string 进行比较?我该如何解决这个问题?
// this function checks if the file contains the *string
bool checkIfMatch(char *string, FILE *file) {
while (true) {
char buff[1024];
fgets(buff, sizeof buff, file);
if (buff == NULL)
break;
char *substring=strstr(buff, string);
if ((strcmp(buff, substring)) == 0)
return true;
}
return false;
}
最佳答案
您不能保证 substring
是非 NULL。所以你需要测试它:
bool checkIfMatch(char *string, FILE *file) {
char buff[1024];
while (fgets(buff, sizeof buff, file)) {
char *substring=strstr(buff, string);
if (substring && !strcmp(buff, substring))
return true;
}
return false;
}
其他问题:
在您的代码中,
if (buff == NULL) break;
永远不会导致中断。您需要测试fgets
的返回值。 (参见 WhozCraig 的评论)fgets
保留回车符,这可能不是您想要的。strstr/strcmp 很困惑:您可能只需要
strcmp
,或者可能只需要strstr
。如果文件中的一行超过 1022 个字符,那么您可能会找不到字符串。
关于c - 在 C 中使用 strcmp 的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21655050/