Thread: Dynamic fgets

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    84

    Dynamic fgets

    Hi all,

    I want to change following function to a "dynamic" fgets for string with unknown length and without any use of a buffer.Could someone give me an example with realloc please?

    Code:
    ...
    int ReadInputToTree(
     WORD **DestTree, 
     size_t *Treecount, 
     FILE *Input)
    {
       int Status = SUCCESS;
       char Buf[8192] = {0};
       char *Word = NULL;
       while(fgets(Buf, sizeof Buf, Input) != NULL)
       {
          Word = strtok(Buf, NONALPHA);
          while(Status == SUCCESS&& Word != NULL)
          {
             Status = AddToTree(DestTree, Treecount, Word);
             if(Status == SUCCESS)
             {
               Word = strtok(NULL, NONALPHA);
             }
          }
       }
       return (Status);
    }
    ...

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The idea is that fgets stores the newline from the read if there is space for it, so if you didn't detect the newline in the fgets read, you know that there's possibly still more to read (or maybe the newline is the only thing next, but that's fine).
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fgets after scanf, skips over fgets?
    By willane1965 in forum C Programming
    Replies: 1
    Last Post: 08-17-2014, 11:13 PM
  2. Dynamic 2D through fgets
    By Wolferion in forum C Programming
    Replies: 2
    Last Post: 11-29-2012, 04:45 AM
  3. Replies: 10
    Last Post: 12-03-2011, 02:26 PM
  4. Dynamic allocation with fgets?
    By nutzu2010 in forum C Programming
    Replies: 17
    Last Post: 02-09-2011, 09:56 AM
  5. fgets()
    By Ideswa in forum C Programming
    Replies: 3
    Last Post: 06-27-2007, 11:14 AM

Tags for this Thread