views:

400

answers:

4

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:

PES 2009

Konami

.

.

.

A: 

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.

ammoQ
A: 

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);
}
pmg
+1  A: 
Ass3mbler
this will take into account also the newline at the end of each row and will handle it correctly
Ass3mbler
A: 

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

vitaly.v.ch