我在计算机上使用Codeblock,并且还使用dev ++对其进行了检查,当我将test.txt作为输入文件和stop.txt给出时,它们都给出相同的正确结果。https://pastebin.com/Z8CPnJNd(test.txt)和https://pastebin.com/qhLU9QV3(stop.txt)
但是,当我在gcc中使用CentOs OS时,它不会从结构列表中删除停用词。例如,必须删除字符串of
。
我运行终端,使用命令gcc main.c -o main -std=c99
,然后使用./main
我不知道是否有任何const引起了问题,但我已经检查过了。
这是应该执行的部分
typedef struct _word {
char *s; /* the word */
int count; /* number of times word occurs */
int *line_numbers; // Array of line numbers
int num_line_numbers; // Size of the array of line numbers
char *fileno;
} word;
// Creating a struct to hold the data. I find it's easier
typedef struct {
word *words; // The array of word structs
int num_words; // The size of the array
} word_list;
char *strlower(char *s) {
for (size_t i = 0; s[i]; i++) {
s[i] = (char)tolower((unsigned char)s[i]);
}
return s;
}
int remove_word(word_list *words, const char *word_to_delete) {
int found = 0;
for (int i = 0; i < words->num_words; i++) {
if (!strcmp(words->words[i].s, word_to_delete)) {
// Calc number of words after found word
int number_of_words_to_right = words->num_words - i - 1;
// Free mem
free(words->words[i].s);
free(words->words[i].line_numbers);
free(words->words[i].fileno);
if (--words->num_words == 0) {
free(words->words);
words->words = NULL;
} else {
// Copy remaining words if any
memcpy(&words->words[i], &words->words[i + 1],
sizeof(word) * number_of_words_to_right);
// Resize the array (technically not required)
word *tmp = realloc(words->words, sizeof(word) * words->num_words);
if (tmp != NULL)
words->words = tmp;
}
found++;
i--; // restart from the same index in the loop
}
}
return found;
}
main:
int main() {
int option = 1;
word_list *words = calloc(sizeof(word_list), 1);
if (words == NULL) {
fprintf(stderr, "cannot allocate memory\n");
return 1;
}
read_file(words, "test.txt");
if (option != 0) {
char s[1000];
FILE *file = fopen("stop.txt", "r"); /* should check the result */
if (file == NULL) {
fprintf(stderr, "cannot open %s\n", "stop.txt");
} else {
while (fgets(s, sizeof(s), file)) {
char *word = strtok(s, " \n");
while (word != NULL) {
remove_word(words, strlower(word));
word = strtok(NULL, " \n");
}
}
fclose(file);
}
}
printlist(words);
for (int i = 0; i < words->num_words; i++) {
free(words->words[i].s);
free(words->words[i].line_numbers);
free(words->words[i].fileno);
}
free(words->words);
free(words);
return 0;
}
Code:
https://pastebin.com/aWWHyeyi