1

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 :)

Yaser Sleiman
  • 95
  • 1
  • 3
  • 12
  • looks like you're passing a FILE* when the strtok function takes a char*... also, the file has been closed... http://linux.die.net/man/3/strtok – Homer6 May 18 '13 at 04:53
  • @Homer6 - You're right. I fixed the file closing part. Still looking at the FILE*/char* part. – Yaser Sleiman May 18 '13 at 04:59
  • You should probably use fread to read the file's contents into a string first... http://www.manpagez.com/man/3/fread/ see if you can google to find examples and try to combine the examples... also, like @JimBalter said, posting and googling compiler errors helps a lot – Homer6 May 18 '13 at 05:02
  • @Homer6 - Well the actual thing I need to do is read it into a 2D linked list. I'm still a noob and investigating how to do that. I thought I'd learn and get the reading in data part right first. – Yaser Sleiman May 18 '13 at 05:06
  • @YaserSleiman I'd recommend c++ for that: http://www.cplusplus.com/reference/list/list/push_back/ also, this lecture is worth a million bucks, if you have the time (watch all of them if you can and buy the text) https://www.youtube.com/watch?v=Ps8jOj7diA0 – Homer6 May 18 '13 at 05:13
  • @Homer6 Thanks Homer. I'd love to know how to code in C++ but this is a C course and we're not allowed to use C++. C++ is next year =) – Yaser Sleiman May 18 '13 at 05:18
  • @YaserSleiman The video is for C... trust me... it's a great investment – Homer6 May 18 '13 at 05:31
  • @Homer6 I will definitely watch the video. It looks interesting. I'll watch all, hopefully they will help me understand C better. I've updated my code. I'm using fread now but it's still not working as expected. – Yaser Sleiman May 18 '13 at 05:46

2 Answers2

2

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!
Community
  • 1
  • 1
Homer6
  • 15,034
  • 11
  • 61
  • 81
  • Oh wow! Helpful much?! Thank you so much @Homer6. Currently studying your code. – Yaser Sleiman May 19 '13 at 19:17
  • I see what you've done. You've made it so that each line before the token gets input as a string and then printed. But I still don't understand what errors would come up from the ferror function. I mean errors might come up, but they could all be different. So if I was to use ferror as a way of feedback to the user, I'd need a new ferror function per error. Is that right? Or does ferror catch all errors? Thank you for all help Homer. I greatly appreciate it. :) – Yaser Sleiman May 19 '13 at 19:22
  • The ferror function is for "File Errors". It's meant to catch any errors that would come up on the fgets function. My understanding is that it will trigger on all errors and that you wouldn't need to print the error message with perror, you could just detect the error and give a generic error message. The main thing to keep in mind is that, in c, you need to handle errors from every function call. – Homer6 May 19 '13 at 20:13
  • Hmmm. I see. But isnt that in C++ and Java as well? I mean I remember studying exceptions to catch everything in Java, and C++ I've never learnt nor gone near it yet. Thanks though Homer, you've been awesome help. Also, that link you sent me: Wow. I can't believe I hadn't seen that before, and there are so many lessons continuing too. I might just have to sit through and watch them all. – Yaser Sleiman May 20 '13 at 16:56
  • There are no exceptions in C. There are exceptions is C++ and Java. I'm glad you like the lecture. IMHO, Jerry Cain is one of the best comp sci profs around (which is probably why he's at Stanford). Here is the textbook for that course: http://www.amazon.com/Computer-Systems-Programmers-Perspective-2nd/dp/0136108040 – Homer6 May 20 '13 at 18:19
  • Hmmm I see. Also, at Jerry Cain, I've yet to see more for him but I already like him more than my lecturer. He does seem amazing.. – Yaser Sleiman May 21 '13 at 10:36
  • Homer, Do you mind if I ask you more questions sometime? Like whenever I've run into trouble? I understand if this is ridiculous of me to ask, I mean you have your own life of course. I just like your knowledge with C and you seem to be pretty active also. I would greatly appreciate it if maybe I could do that. I'm just a simple student trying to learn C after learning Java (which in my opinion should have been taught the other way around - C first, Java/C++ second). :) – Yaser Sleiman May 21 '13 at 10:41
  • It's no problem Yaser. IMHO, having a mentor on this stuff when you're getting started can make a big difference. However, I'm not advanced by any means, just intermediate. If you post your contact info in your profile, I'll reach out to you. – Homer6 May 21 '13 at 16:07
  • Thanks a lot Homer! :) It does make a big difference having a helping hand to put me on the right track. Thank you again. I'll update my profile now. :) – Yaser Sleiman May 22 '13 at 13:44
  • @YaserSleiman Sorry, it doesn't appear. Did you put it in the description? – Homer6 May 23 '13 at 01:54
  • Homer, Sorry I thought you were able to see my email field. I have inserted it into my description. As always, thanks. – Yaser Sleiman May 23 '13 at 16:15
0
//  fread(buffer, strlen(number)+1, 1, fp);
    fscanf(fp, "%s", buffer);//read "hello"
    printf("%s, ", buffer);
    fscanf(fp, "%s", buffer);//read "world"
    printf("%s\n", buffer);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70