Demo programming

Moderators: None (Apply to moderate this forum)
Number of threads: 150
Number of posts: 326

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Edit Report
fstream-reading one line at a time Posted by stressed on 13 Jun 1999 at 10:27 PM
I am A stress out student, I have to write a program that reads one line from an input file into a string.<br>
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<br>
does any one know how to do this?


Edit Report
Re: fstream-reading one line at a time Posted by Sepi on 16 Jul 1999 at 4:36 AM
: I am A stress out student, I have to write a program that reads one line from an input file into a string.<br>
: 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<br>
: does any one know how to do this?<p>
I think that you are on wrong page now (how this is connected to demo programming?), but still...<br>
Use fscanf() function.<br>
Here is the example:<p>
char Buf[100];<br>
FILE *fp;<br>
fp=fopen(Filename,"rb");<br>
fscanf(fp,"%s",Buf); // 1<br>
fscanf(fp,"%s\n",Buf); // 2<br>
fscanf(fp,"%[^\n]s\n"); // 3<p>
Comment 1:<br>
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)<p>
Comment 2:<br>
This reads string and then it reads EOL also.<p>
Comment 3:<br>
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...<p>
Note that you can't use code like this:<p>
char *Buf;<br>
fscanf(fp,"%s",Buf);<p>
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...<br>
This will fix it:<p>
char *Buf;<br>
Buf=(char *)malloc(100);<br>
fscanf(fp,"%s",Buf);<br>
free(Buf);<p>
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.<p>
I hope that this helps you!<p>
-Sepi





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.