我只是想在一个字符串返回的每一个字,但strtok的返回的第一个字,然后紧随其后空:C:的strtok返回第一个值,然后NULL
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()是问题。
如果我用char test[] = "this is a test string"
而不是filestr调用strtok,那么它正确地返回每个单词。但是,如果我将get_file()获得的文件内容设置为“this is a string”,那么它将返回“this”,然后返回(null)。
按要求,这里是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;
}
'get_file()'的代码在哪里? – FatalError 2012-02-05 02:33:01
@FatalError我添加了get_file()的代码 – 2012-02-05 02:38:26
一个问题 - 您的printf()在第二个strtok()之后,因此您无法看到打印文件的第一个单词,您必须看到第二个单词?该代码看起来很适合我 - 你确定*你发布了失败的确切代码吗? – peterept 2012-02-05 02:44:42