By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,888 Members | 1,553 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,888 IT Pros & Developers. It's quick & easy.

Using fgets() to store string in memory

P: n/a
Hello

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.

Thanks

Peter Mount
in**@petermount.au.com
Nov 14 '05 #1
Share this Question
Share on Google+
26 Replies


P: n/a
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.


No it can't. However, you can try ggets.zip from:

<http://cbfalconer.home.att.net/download/>

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #2

P: n/a


Peter Mount wrote:
Hello

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.


It can solve the problem of attempting to read a stream that may
be more characters than the size of the declared array (as opposed
to function gets).

The synopsis of the function is:
#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);
Question 7.1 of the faq can over one possible use of the function where
the stream is stdin. http://www.eskimo.com/~scs/C-faq/q7.1.html

Use a c.l.c googles search or a web search for online resource of the
function. Seek offline resources including the Standard. A newsgroup
discussion is probably not the best resource for a comprehensive
discussion or descripition of the function.

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #3

P: n/a
In <40**********@news.iprimus.com.au> "Peter Mount" <in**@petermount.au.com> writes:
What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.


Nonsense! Read the specification of fgets() in your favourite C book
instead of "understanding" things.

BTW, IMHO, fgets() is a perfectly useless library function, invented by
someone who skipped the design phase.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #4

P: n/a
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.


No it can't. However, you can try ggets.zip from:

<http://cbfalconer.home.att.net/download/>


Are you *sure* it solves the OP problem? Please engage your brain
*before* replying ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #5

P: n/a
In <2h************@uni-berlin.de> Al Bowers <xa******@rapidsys.com> writes:

Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.


It can solve the problem of attempting to read a stream that may
be more characters than the size of the declared array (as opposed
to function gets).


Come to think of it, it is gets() that actually solves the OP problem ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #6

P: n/a
syntax:
char *fgets( char *str, int num, FILE *stream);

"Peter Mount" <in**@petermount.au.com> wrote in message
news:40**********@news.iprimus.com.au...
Hello

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.

Thanks

Peter Mount
in**@petermount.au.com

Nov 14 '05 #7

P: n/a
And somewhere around the time of 05/19/2004 07:17, the world stopped and
listened as Peter Mount contributed the following to humanity:
Hello

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.

Thanks

Peter Mount
in**@petermount.au.com


char line[100];

int main()
{
printf("Prompt: ");
fgets(line, sizeof(line), stdin);
printf("String: %s\n", line);
}
--
Daniel Rudy

Remove nospam, invalid, and 0123456789 to reply.
Nov 14 '05 #8

P: n/a
In article <c8**********@sunnews.cern.ch>, Dan Pop wrote:
In <2h************@uni-berlin.de> Al Bowers <xa******@rapidsys.com> writes:

Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has
more characters than the size of the declared array.


It can solve the problem of attempting to read a stream that may
be more characters than the size of the declared array (as opposed
to function gets).


Come to think of it, it is gets() that actually solves the OP
problem ;-)


Is that like punching yourself in the arm to cure a headache?

--
Neil Cerutti
"The barbarian seated himself upon a stool at the wenches side, exposing
his body, naked save for a loin cloth brandishing a long steel broad
sword..." --The Eye of Argon
Nov 14 '05 #9

P: n/a
Daniel Rudy wrote:
char line[100];

int main()
{
printf("Prompt: ");
fgets(line, sizeof(line), stdin);

^^^^^^
As you may know, the parentheses are unnecessary.

Nov 14 '05 #10

P: n/a
Dan Pop wrote:
CBFalconer <cb********@yahoo.com> writes:
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.


No it can't. However, you can try ggets.zip from:

<http://cbfalconer.home.att.net/download/>


Are you *sure* it solves the OP problem? Please engage your brain
*before* replying ;-)


It solves his problem in that it allows him to get a string from
the operator without worrying about the length of that string, and
elides any final '\n'. He will have to observe the published
calling parameters, and consider how he treats the pointer to the
line after use. He might have to actually read the header and/or
the usage examples.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #11

P: n/a
Dan Pop wrote:
.... snip ...
Come to think of it, it is gets() that actually solves the OP
problem ;-)


You are innately evil, and are attempting to corrupt the innocent
youths of the world :-)

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #12

P: n/a

"Dan Pop" <Da*****@cern.ch> wrote in message
news:c8**********@sunnews.cern.ch...
In <40**********@news.iprimus.com.au> "Peter Mount" <in**@petermount.au.com> writes:
What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that hasmore characters than the size of the declared array.


Nonsense! Read the specification of fgets() in your favourite C book
instead of "understanding" things.

BTW, IMHO, fgets() is a perfectly useless library function, invented by
someone who skipped the design phase.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de


I might miss something here. Why is fgets useless? I can see that using a
number of other library functions the same results can be achieved as with
fgets, but I still do not see why it is badly designed. From a API
development point of view I would say it covers everything needed to be
simple but complete in it's functionality. I'm just curious to the reason
for the comment.

Nov 14 '05 #13

P: n/a

"Peter Mount" <in**@petermount.au.com> wrote
What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that > has more characters than the size of the declared array.


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

int main(void)
{
char buff[256];

printf("Enter a string\n");
if( fgets(stdin, buff, sizeof buff) == 0)
{
printf("Input error\n");
exit(EXIT_FAILURE);
}
ptr = strchr(buff, '\n');
if(!ptr)
{
printf("Line too long\n"):
exit(EXIT_FAILURE);
}
*ptr = 0;
printf("Your string ***%s***\n", buff);
exit(0);
}
Nov 14 '05 #14

P: n/a

"Neil Cerutti" <ho*****@yahoo.com> wrote in message
news:2h************@uni-berlin.de...
In article <c8**********@sunnews.cern.ch>, Dan Pop wrote:
In <2h************@uni-berlin.de> Al Bowers <xa******@rapidsys.com> writes:
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that has more characters than the size of the declared array.
It can solve the problem of attempting to read a stream that may
be more characters than the size of the declared array (as opposed
to function gets).
Come to think of it, it is gets() that actually solves the OP
problem ;-)

While on the subject, what is Morris doing these days???

Is that like punching yourself in the arm to cure a headache?

--
Neil Cerutti
"The barbarian seated himself upon a stool at the wenches side, exposing
his body, naked save for a loin cloth brandishing a long steel broad
sword..." --The Eye of Argon

Nov 14 '05 #15

P: n/a


Malcolm wrote:
"Peter Mount" <in**@petermount.au.com> wrote
What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string that >
has more characters than the size of the declared array.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
char buff[256];

printf("Enter a string\n");


puts("Enter a string");

or printf("Enter a string: ");
fflush(stdout);
if( fgets(stdin, buff, sizeof buff) == 0)
The synopsis of the function is:
#include <stdio.h>
char *fgets(char * restrict s, int n,
FILE * restrict stream);
{
printf("Input error\n");
exit(EXIT_FAILURE);
}
ptr = strchr(buff, '\n');
What is ptr?
if(!ptr)
{
printf("Line too long\n"):
exit(EXIT_FAILURE);
}
*ptr = 0;
printf("Your string ***%s***\n", buff);
exit(0);
}


Why did you post such garbage? This code? is an example
of why the OP should not use a newsgroup for a comprehensive
question on how to code with the function fgets.

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #16

P: n/a

"Frits Germs" <fr*********@t-online.de> wrote in message
I might miss something here. Why is fgets useless? I can see that
using a number of other library functions the same results can be
achieved as with fgets, but I still do not see why it is badly
designed. From a API development point of view I would say it
covers everything needed to be simple but complete in it's
functionality. I'm just curious to the reason for the comment.

Imagine we have the following

char buff[N];

....

gets(buff);

this is fine until someone enters aline of N or more characters, when you
get a buffer overflow and undefined behaviour.

Now the temptation is to replace this with

fgets(buff, N, stdin);

However this solution is if anything worse than what has gone before. With
gets() we had undefined behaviour - which probably means a crash with the
message "segmentation fault", with fgets() we have wrong behaviour - silent
truncation of the string, so "message to court martial to be put into
execution pending decision of civilian court" becomes "sentence of court
martial to be put into execution pending decision of civilian". No compiler
can warn about or correct wrong behaviour, because it has no insight into
the purpose of the program.

fgets() can of course be used correctly, but most programmers aren't capable
of doing so - witness the reply to my post showing the correct way to check
for overflow conditons.


Nov 14 '05 #17

P: n/a
On Thu, 20 May 2004 22:35:35 +0100, "Malcolm"
<ma*****@55bank.freeserve.co.uk> wrote:

"Frits Germs" <fr*********@t-online.de> wrote in message
I might miss something here. Why is fgets useless? I can see that
using a number of other library functions the same results can be
achieved as with fgets, but I still do not see why it is badly
designed. From a API development point of view I would say it
covers everything needed to be simple but complete in it's
functionality. I'm just curious to the reason for the comment.
Imagine we have the following

char buff[N];

...

gets(buff);

this is fine until someone enters aline of N or more characters, when you
get a buffer overflow and undefined behaviour.

Now the temptation is to replace this with

fgets(buff, N, stdin);

However this solution is if anything worse than what has gone before. With
gets() we had undefined behaviour - which probably means a crash with the
message "segmentation fault", with fgets() we have wrong behaviour - silent
truncation of the string,


The truncation need not be silent. I have code which reads and parses
lines from configuration files which have a specified maximum length.
Over-length lines are reported as such and the input is flushed to the
next newline.
so "message to court martial to be put into
execution pending decision of civilian court" becomes "sentence of court
martial to be put into execution pending decision of civilian". No compiler
can warn about or correct wrong behaviour, because it has no insight into
the purpose of the program.

fgets() can of course be used correctly, but most programmers aren't capable
of doing so - witness the reply to my post showing the correct way to check
for overflow conditons.


--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #18

P: n/a

"Alan Balmer" <al******@att.net> wrote in message
gets(buff);

Now the temptation is to replace this with

fgets(buff, N, stdin);

However this solution is if anything worse than what has gone
before.


The truncation need not be silent. I have code which reads and
parses lines from configuration files which have a specified
maximum length.
Over-length lines are reported as such and the input is flushed to
the next newline.

It is possible to use fgets() correctly. From experience this isn't commonly
done, even by experienced programmers.
By the time you have used strchr() to check for the trailing newline, and
gobbled input to prevent the next function reading a partial line, it is
probably easier to write your own fgetline() function based on fgetc().
Nov 14 '05 #19

P: n/a
On Thu, 20 May 2004 23:50:15 +0100, "Malcolm"
<ma*****@55bank.freeserve.co.uk> wrote:

"Alan Balmer" <al******@att.net> wrote in message
>gets(buff);

>Now the temptation is to replace this with
>
>fgets(buff, N, stdin);
>
>However this solution is if anything worse than what has gone
>before.


The truncation need not be silent. I have code which reads and
parses lines from configuration files which have a specified
maximum length.
Over-length lines are reported as such and the input is flushed to
the next newline.

It is possible to use fgets() correctly. From experience this isn't commonly
done, even by experienced programmers.
By the time you have used strchr() to check for the trailing newline, and
gobbled input to prevent the next function reading a partial line, it is
probably easier to write your own fgetline() function based on fgetc().

I've done it that way, too (in fact the current implementation uses
fgetc(), after ([OT]) testing to see that the efficiency was about the
same on the target platform.) Not much different - the gobble part is
the same either way, and there are ways of detecting the full buffer
without using strchr().

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #20

P: n/a
On Wed, 19 May 2004 15:26:33 +0000, Dan Pop wrote:
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.


No it can't. However, you can try ggets.zip from:

<http://cbfalconer.home.att.net/download/>


Are you *sure* it solves the OP problem? Please engage your brain
*before* replying ;-)


Dan, it solves the general problem in a rather elegant way and I think you
know it.

Given your beef with the silent truncation behavior of fgets(), fggets()
should be a breath of fresh air: Automatic reallocation with a noisy
failure if it fails to grab any more core. You need to call free() on the
pointer you sent in, but, as you commonly say, it's simply a matter of
"engaging the brain".

"Engage the brain" indeed. If it were any simpler, it would be C++. ;-)

--
yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
To email me, rot13 and convert spelled-out numbers to numeric form.
"Makes hackers smile" makes hackers smile.

Nov 14 '05 #21

P: n/a
In <c8*************@news.t-online.com> "Frits Germs" <fr*********@t-online.de> writes:
"Dan Pop" <Da*****@cern.ch> wrote in message
news:c8**********@sunnews.cern.ch...

BTW, IMHO, fgets() is a perfectly useless library function, invented by
someone who skipped the design phase.

I might miss something here. Why is fgets useless? I can see that using a
number of other library functions the same results can be achieved as with
fgets, but I still do not see why it is badly designed. From a API
development point of view I would say it covers everything needed to be
simple but complete in it's functionality. I'm just curious to the reason
for the comment.


I have addressed this issue countless times, in this very newsgroup, so
Google is your friend.

Basically, after writing the code using fgets in a bullet-proof manner,
you realise that a getc-based solution would have been simpler.

If truncation of superlong lines is what you want, scanf is your friend.
Every time I've challenged someone to do that with fgets in a bullet-proof
manner, I've got a broken solution, missing one failure mode or another.

If truncation is not an option, a solution that can handle arbitrary
long lines via dynamic input buffer reallocation is needed and fgets
doesn't even come close.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #22

P: n/a
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
Dan Pop wrote:
CBFalconer <cb********@yahoo.com> writes:
Peter Mount wrote:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.

No it can't. However, you can try ggets.zip from:

<http://cbfalconer.home.att.net/download/>


Are you *sure* it solves the OP problem? Please engage your brain
*before* replying ;-)


It solves his problem in that it allows him to get a string from
the operator without worrying about the length of that string, and
elides any final '\n'.


But this is not his *stated* problem. That's why I asked you to engage
your brain before replying ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #23

P: n/a
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
Dan Pop wrote:

... snip ...

Come to think of it, it is gets() that actually solves the OP
problem ;-)


You are innately evil, and are attempting to corrupt the innocent
youths of the world :-)


I was merely giving him what he was asking for:

What's the syntax for using fgets() to store a string in memory? I
understand that fgets() can solve the problem of storing a string
that has more characters than the size of the declared array.
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^

Unless I'm missing something, gets() works far better than fgets() for
this purpose ;-)

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #24

P: n/a
August Derleth <se*@sig.now> wrote:
Given your beef with the silent truncation behavior of fgets(), fggets()
should be a breath of fresh air: "Engage the brain" indeed. If it were any simpler, it would be C++. ;-)


Ok, this tells me I should never use the ggets package: if it were any
simpler, it would be an over-designed, over-complicated, under-
understood monstrosity, with delusions of grandeur. Think how unusable
it must be now...

Richard
Nov 14 '05 #25

P: n/a
On Mon, 24 May 2004 08:24:00 +0000, Richard Bos wrote:
August Derleth <se*@sig.now> wrote:
Given your beef with the silent truncation behavior of fgets(), fggets()
should be a breath of fresh air:

"Engage the brain" indeed. If it were any simpler, it would be C++. ;-)


Ok, this tells me I should never use the ggets package: if it were any
simpler, it would be an over-designed, over-complicated, under-
understood monstrosity, with delusions of grandeur. Think how unusable
it must be now...


Heh. Very funny. ;-)

--
yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
To email me, rot13 and convert spelled-out numbers to numeric form.
"Makes hackers smile" makes hackers smile.

Nov 14 '05 #26

P: n/a
Richard Bos wrote:
August Derleth <se*@sig.now> wrote:
Given your beef with the silent truncation behavior of fgets(),
fggets() should be a breath of fresh air:

"Engage the brain" indeed. If it were any simpler, it would be
C++. ;-)


Ok, this tells me I should never use the ggets package: if it
were any simpler, it would be an over-designed, over-complicated,
under-understood monstrosity, with delusions of grandeur. Think
how unusable it must be now...


Decide for yourself:

<http://cbfalconer.home.att.net/download/ggets.zip>

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?

Nov 14 '05 #27

This discussion thread is closed

Replies have been disabled for this discussion.