Printing tokenized data from file in C

Yaser Sleiman picture Yaser Sleiman · May 18, 2013 · Viewed 12.2k times · Source

I've been trying to read in data from a file by tokenizing it first. In this example, I've made it so that it asks you to first input the data in yourself (which I've made sure works), and then read it in but tokenize with spaces. So if I was to enter 'Hello World' it should return: 'Hello, World'. Here's my code.

    char fname[] = "myfile";
FILE *fp;
fp = fopen(fname, "w+");
char buffer[20];

sprintf(prompt, "Enter your string: ", MAX_TAN_INPUT);
getString(number, MAX_TAN_INPUT, prompt);
printf("\n");

if (fp == NULL)
{
    fprintf(stderr, "Unable to open file %s\n", fname);
}
else
{
    printf("YAYYY. It opened!\n");

    fprintf (fp, "%s\n", number);

    fseek(fp, SEEK_SET, 0);
    fread(buffer, strlen(fp)+1, 1, fp);
    printf("%s\n", buffer);
    {
        /* No more data read. */
    }
}

printf ("HERE\n");

fclose(fp);

Any help would be greatly appreciated guys :)

Answer

Homer6 picture Homer6 · May 19, 2013

Below is the c version. However, I must say that I prefer the c++ version. :-) https://stackoverflow.com/a/3910610/278976

main.c

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

#define BUFFER_SIZE 1024


int main( int argc, char** argv ){

    const char *delimiter_characters = " ";
    const char *filename = "file.txt";
    FILE *input_file = fopen( filename, "r" );
    char buffer[ BUFFER_SIZE ];
    char *last_token;

    if( input_file == NULL ){

        fprintf( stderr, "Unable to open file %s\n", filename );

    }else{

        // Read each line into the buffer
        while( fgets(buffer, BUFFER_SIZE, input_file) != NULL ){

            // Write the line to stdout
            //fputs( buffer, stdout );

            // Gets each token as a string and prints it
            last_token = strtok( buffer, delimiter_characters );
            while( last_token != NULL ){
                printf( "%s\n", last_token );
                last_token = strtok( NULL, delimiter_characters );
            }

        }

        if( ferror(input_file) ){
            perror( "The following error occurred" );
        }

        fclose( input_file );

    }

    return 0;

}

file.txt

Hello there, world!
How you doing?
I'm doing just fine, thanks!

linux shell

root@ubuntu:/home/user# gcc main.c -o example
root@ubuntu:/home/user# ./example
Hello
there,
world!

How
you
doing?

I'm
doing
just
fine,
thanks!