Re: How to take in a string of any size?

From: SM Ryan (wyrmwif_at_tango-sierra-oscar-foxtrot-tango.fake.org)
Date: 08/22/04


Date: Sun, 22 Aug 2004 15:18:23 -0000

zalzon <zalzonishappy@zalll.com> wrote:
# On Sun, 22 Aug 2004 02:07:17 -0600, William L. Bahn wrote:
#
# > You could write it to a file, counting the characters as you go,
# > and then allocate the memory and read it back in.
#
# Except you have to read the string in first before you write it to a file
# stream... which leads to the original question of how do you read a string
# of unspecified size in and store it.....

char *s = 0; int m = 0,n = 0,c; FILE *f = ...;
*s = 0;
while ((c=fgetc(f))!=EOF) {
        if (n+2>=m) {m = 2*(n+2); s = realloc(s,m);}
        s[n++] = c; s[n] = 0;
        if (c=='\n') {s = realloc(s,n+1); break;}
}
if (s) {
        ....
}else {
        end of file....
}

--
SM Ryan http://www.rawbw.com/~wyrmwif/
This is one wacky game show.


Relevant Pages

  • Re: String Literals
    ... read-only section of memory. ... to retrieve specific characters, but limits your ability to change ... I can imagine some buggy compilers messing it ... the contexts in which a string ...
    (comp.lang.c.moderated)
  • Re: Blowfish encryption
    ... the source string will be padded to the next ... correct for Harbour/HWGUI but for good old 16 bit Clipper it ... allocate up to 64K, so any data/field longer than this will fail. ... an unrecoverable error 5304 (conventional memory exhausted). ...
    (comp.lang.clipper)
  • Re: Function speed, which is fast
    ... what is happening is the string is getting resized and memory allocation ... or you could create a dynamic memory chuck pointed via a PCHAR.. ... allocate like a 100K byte Pchar buffer. ... > function examines every single character of the plain text file. ...
    (comp.lang.pascal.delphi.misc)
  • Re: Why crash ?
    ... Yes, but naively, I would assume that the optimal buffer size ... depended on a certain number of characters, ... small string optimization is that the std::string object has a certain ... If you allocate dynamic storage, the string object has to store ...
    (microsoft.public.vc.language)
  • Re: This is getting really weird.
    ... I thought 4 bytes for reference count and 4 for string length. ... > There should be no memory allocation for that line. ... > manager may allocate more space than requested for its own efficiency. ... > that New returned with a pointer to the string constant. ...
    (alt.comp.lang.borland-delphi)