2012-02-05 73 views
0

我只是想在一个字符串返回的每一个字,但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; 
} 
+0

'get_file()'的代码在哪里? – FatalError 2012-02-05 02:33:01

+0

@FatalError我添加了get_file()的代码 – 2012-02-05 02:38:26

+1

一个问题 - 您的printf()在第二个strtok()之后,因此您无法看到打印文件的第一个单词,您必须看到第二个单词?该代码看起来很适合我 - 你确定*你发布了失败的确切代码吗? – peterept 2012-02-05 02:44:42

回答

3

你通过在它空字符的二进制文件?

get_file()被正确地返回一个字符缓冲区,但(例如),如果我给你的功能的PNG文件缓冲器看起来像这样

(GDB)p个数据[0] @ 32 $ 5 =“\ 211PNG \ r \ n \ 032 \ n \ 000 \ 000 \ 000 \ rIHDR \ 000 \ 000 \ 003 \ 346 \ 000 \ 000 \ 002 \ 230 \ b \ 006 \ 000 \ 000 \ 000 \ 376?”

您可以看到,在PNG \ r \ n之后,它具有空字符,因此您不能真正将get_file()的返回值视为字符串。你需要把它当作一个字符数组来处理,并且手动返回总长度,而不是依赖null终止。

然后,就像它目前写的那样,你不能依靠strtok,因为它在遇到你的第一个空字符后就停止处理。您可以通过对数据进行传递并将所有空字符转换为其他字符来解决此问题,或者可以实现可在给定长度的缓冲区上工作的strtok版本。

+0

谢谢。不幸的是,我带领我们离开了这条线索,认为问题出在我最初发布的代码中。我提交了一篇文章,指出真正的问题,但我看不出如何解决这个问题。看到如何实现get_file()后编辑 – 2012-02-05 03:02:07

+0

。看起来你解决了你的问题。 :) – Bren 2012-02-05 03:06:22

相关问题