First off, this is my first c program and i am by no means a programmer so ignore me if i don't meet your standard and let those willing to show me how it is done respond.

Problem Statement:
I am trying to use "strtok" to tokenize the strings in my file to screen.

Say i have a file "samplefile" which contains three lines:
one two three four five six seven
one two three four five six seven
one two three four five six seven

What i am trying to accomplish eventually is to read the strings i specify in the array (it is a rather long problem but i want to write the code in increments so i understand what each line of code does and can solve similar problems in the future), right now i want my code to just read the file and spit out the tokenized result but my code only prints the first string on each line:

My Output:
one
one
one

Desired output
one two three four five six seven
one two three four five six seven
one two three four five six seven

I would appreciate any help.

Thanks in advance.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>

main()

{
char line [120];
FILE *fp;
fp=fopen("samplefile", "r");

if (fp == NULL) perror ("error opening file");
else
	{
	fgets (line, sizeof (line), fp);
	while (fgets(line, sizeof (line),fp))
	{
			
		char* t=strtok(line," ");
		if (t != NULL);
{				
		printf("%s\n",line);
			
		
		
	}
}
}
fclose(fp);
return(0);
}

Dani AI

Generated

A couple of small pitfalls explain why you only see the first word per line. First, you have an extra fgets before the loop, so the first line is discarded. Second, a stray semicolon after the if makes the following block run unconditionally. Also, strtok replaces delimiters with NUL characters and keeps internal state, so call it in a loop for each line, and include the newline in your delimiter set. If you later need thread safety or nested tokenization, prefer strtok_r (or strtok_s on Windows).

Here is a compact, robust pattern that preserves one line per output line and collapses any whitespace to single spaces:

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *fp = fopen("samplefile", "r");
    if (!fp) { perror("error opening file"); return 1; }

    char line[120];
    while (fgets(line, sizeof line, fp)) {
        char *save = NULL;
        char *tok = strtok_r(line, " \t\r\n", &save);
        int first = 1;
        while (tok) {
            if (!first) putchar(' ');
            fputs(tok, stdout);
            first = 0;
            tok = strtok_r(NULL, " \t\r\n", &save);
        }
        putchar('\n');
    }
    fclose(fp);
    return 0;
}

Notes:

  • Using " \t\r\n" splits on any whitespace and strips the trailing newline from fgets.
  • Printing with a spacer guard (first) avoids a trailing space.

See the strtok and strtok_r docs on cppreference and the fgets reference at cppreference fgets for details and caveats.

Recommended Answers

All 4 Replies

>>First off, this is my first c program and i am by no means a programmer so ignore me if i don't meet your standard and let those willing to show me how it is done respond.

What a rude first introduction and first impression! Guess I'll just stop reading your post right now. Old proverb -- if you can't take the heat then stay out of the kitchen.

First of all, you're using the if statement in the wrong way(a semicolon before the body)

if (t != NULL);
{
printf("%s\n",line);// here you should use "t" instead of "line"
 
 
 
}

Strtok separates the string in tokens separated by a delimiter string (here " "). Printing the "t" will print the first token at first.

fgets (line, sizeof (line), fp);
char* t=strtok(line," ");
if (t != NULL)
    printf("%s\n",t);

calling strtok for the second time (with NULL as the first argument if you're reading from the same string) will print the second token and so on.If there are no tokens left it will return NULL.

fgets (line, sizeof (line), fp);
char* t=strtok(line," ");/*in the first call the first argument should not be NULL*/
if (t != NULL)
    printf("%s\n",t);
t=strtok(NULL," ");
if (t != NULL)
    printf("%s\n",t);
t=strtok(NULL," ");
if (t != NULL)
    printf("%s\n",t);

So to achieve the output you want you have to do like this:

...
if (fp == NULL)
    perror ("error opening file");
else {
    while(fgets (line, sizeof (line), fp)){
        t=strtok(line," ");
        printf("\n");
        while( t != NULL ) {
            printf( "%s\t",t);
            t = strtok( NULL, " " );
        }
    }
}
...
commented: good info +17

@ Diwakar Wagle..Many Thanks to you - i am indeed grateful.

@ Diwakar Wagle..Many Thanks to you - i am indeed grateful.

Then please give them some rep and mark this thread closed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.