Я просто пытаюсь вернуть каждое слово в строке, но strtok возвращает первое слово, а затем сразу ноль:
int main(int argc, char *argv[]) {
// Get the interesting file contents
char *filestr = get_file(argv[1]);
printf("%s\n", filestr);
char *word;
word = strtok(filestr, ";\"'-?:{[}](), \n");
while (word != NULL) {
word = strtok(NULL, ";\"'-?:{[}](), \n");
printf("This was called. %s\n", word);
}
exit(0);
}
get_file просто открывает указанный путь и возвращает содержимое файла в виде строки,Команда printf("%s\n", filestr);
, показанная выше, успешно распечатывает весь файл.Следовательно, я не думаю, что get_file () является проблемой.
Если я вызову strtok для char test[] = "this is a test string"
вместо filestr, то он корректно возвращает каждое из слов.Однако, если я сделаю содержимое файла, полученного get_file (), как «это строка», тогда он возвращает «это», а затем (ноль).
По запросу вот коддля get_file ():
// Take the path to the file as a string and return a string with all that
// file's contents
char *get_file (char *dest) {
// Define variables that will be used
size_t length;
FILE* file;
char* data;
file = fopen(dest, "rb");
// Go to end of stream
fseek(file, 0, SEEK_END);
// Set the int length to the end seek value of the stream
length = ftell(file);
// Go back to the beginning of the stream for when we actually read contents
rewind(file);
// Define the size of the char array str
data = (char*) malloc(sizeof(char) * length + 1);
// Read the stream into the string str
fread(data, 1, length, file);
// Close the stream
fclose(file);
return data;
}