Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

fstream-reading one line at a time

I am A stress out student, I have to write a program that reads one line from an input file into a string.

I will then do some thing with the string, then I want to read the next line into the same string clobbering the old string doing this over and over until EOF

does any one know how to do this?


Comments

  • : I am A stress out student, I have to write a program that reads one line from an input file into a string.

    : I will then do some thing with the string, then I want to read the next line into the same string clobbering the old string doing this over and over until EOF

    : does any one know how to do this?


    I think that you are on wrong page now (how this is connected to demo programming?), but still...

    Use fscanf() function.

    Here is the example:


    char Buf[100];

    FILE *fp;

    fp=fopen(Filename,"rb");

    fscanf(fp,"%s",Buf); // 1

    fscanf(fp,"%s
    ",Buf); // 2

    fscanf(fp,"%[^
    ]s
    "); // 3


    Comment 1:

    This reads string, I don't know how much of it. Or does it read multiple strings or only until end of line. (And I'am too lazy to test it)


    Comment 2:

    This reads string and then it reads EOL also.


    Comment 3:

    In DJDPP this reads string without EOL and then it reads EOL. I'am not sure if this works on some other compiler. Test it...


    Note that you can't use code like this:


    char *Buf;

    fscanf(fp,"%s",Buf);


    This crashes yours computer cause Buf is a memory pointer wich doesn't point anywhere. (It could point to NULL). And if you read some data to it, crash...

    This will fix it:


    char *Buf;

    Buf=(char *)malloc(100);

    fscanf(fp,"%s",Buf);

    free(Buf);


    Now Buf points to some address. Wich is handled same way as array, but it has to be freed before exiting from program. Or all memory which you have allocated will be unusable - until you reboot.


    I hope that this helps you!


    -Sepi


Sign In or Register to comment.