开发者

Tokenize from a textfile reading into an array in C

How do you tokenize when you read from a file in C?

textfile:

PES 2009;Konami;DVD 3;500.25; 6

Assasins Creed;Ubisoft;DVD;598.25; 3

Inferno;EA;DVD 2;650.25; 7

char *tokenPtr;

fileT = fopen("DATA2.txt", "r"); /* this will not work */
  tokenPtr = strtok(fileT, ";");
  while(tokenPtr != NULL ) {
  printf("%s\n", tokenPtr);
  tokenPtr = strtok(NULL, ";");
}

Would like it to print out开发者_C百科:

PES 2009

Konami

.

.

.


try this:


main()
{
    FILE *f;
    char s1[200],*p;
    f = fopen("yourfile.txt", "r");
    while (fgets(s1, 200, f))
    {

while (fgets(s1, 200, f))
{

    p=strtok(s1, ";\n");

    do
    {
        printf ("%s\n",p);
    }
    while(p=strtok(NULL,";\n"));
}

}

the 200 char size is just an example of course


You must read the file content into a buffer, e.g. line by line using fgets or similar. Then use strtok to tokenize the buffer; read the next line, repeat until EOF.


strtok() accepts a char * and a const char * as arguments. You're passing a FILE * and a const char * (after implicit conversion).

You need to read a string from the file and pass that string to the function.

Pseducode:

fopen();
while (fgets()) {
    strtok();
    /* Your program does not need to tokenize any further,
     * but you could now begin another loop */
    //do {
        process_token();
    //} while (strtok(NULL, ...) != NULL);
}


Using strtok is a BUG. Try strpbrk(3)/strsep(3) OR strspn(3)/strcspn(3).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜