strtok file problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

int main ()
{

    FILE* fp;
    FILE* fo;
    char* filename = "words.txt";
    char* fileo = "output.txt";
    char* pch;
    char test[500];
    fp = fopen(filename,"r");
    if (!(fp = fopen(filename,"r"))) {
    printf("\nCannot open %s for output.\n",filename);
    return 1;
    }

    while (!feof(fp)) {
    char* str=fgets (test , 500 , fp);
    pch = strtok (str," ,.-\t");
    }
    fclose(fp);

    fo = fopen(fileo,"w");
    if (!(fo = fopen(fileo,"w"))) {
    printf("\nCannot open %s for output.\n",fileo);
    return 1;}

    fo = fopen(fileo,"w");
    fputs(pch,fo);

    fclose(fo);
    return 0;
}

input file :
test the 	,whatever.this		program

output file:
test

i want all the words to be there ,it only gives out the first one ,i think its cuz it thinks the file has ended so closes it and doesn't read anymore ,but i can't think how to fix this .,can someone help me out ?

next step is i want to do it on more than just one line .
Last edited on
You have to call strtok in a loop to get the next token.
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
see the example. you're missing the while loop part.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>

int main ()
{

    FILE* fp;
    FILE* fo;
    char* filename = "words.txt";
    char* fileo = "output.txt";
    char* pch;
    char test[500];
    fp = fopen(filename,"r");
    if (!(fp = fopen(filename,"r"))) {
    printf("\nCannot open %s for output.\n",filename);
    return 1;
    }

    while (!feof(fp)) {
    char* str=fgets (test , 500 , fp);
    pch = strtok (str," ,.-\t");
    while (pch != NULL)
  {
     pch = strtok (NULL, " ,.-");
  }

    }
    fclose(fp);

    fo = fopen(fileo,"w");
    if (!(fo = fopen(fileo,"w"))) {
    printf("\nCannot open %s for output.\n",fileo);
    return 1;}

    fo = fopen(fileo,"w");
    fputs(pch,fo);

    fclose(fo);
    return 0;
}
?

still same problem
What's this?
1
2
    fp = fopen(filename,"r");
    if (!(fp = fopen(filename,"r"))) {


And this?
1
2
3
4
5
    fo = fopen(fileo,"w");
    if (!(fo = fopen(fileo,"w"))) {
        //...
    }
    fo = fopen(fileo,"w");


Why are you not picking up the tokens you extract in the loop?
Cuz I am confused ,can you please help
And those I were told so it reads till end of file .

edit: aa nvm ,how hell did i get confused ... lol xD .
Last edited on
You should call fopen once for each file. You're calling it multiple times, the result of doing that is not what you want.
Topic archived. No new replies allowed.