How to read a line of unknown lenght from a file by using dynamic memory allocation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neeru29
    New Member
    • Feb 2009
    • 21

    How to read a line of unknown lenght from a file by using dynamic memory allocation

    I have file, with no of lines. size of of line is unknown.

    I want to read one line at a time.

    I have tried it by using fgets() function, I was able to read apart of the first line and so on...

    Can anyone help me on this..

    regards,
    neeru
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    There are several solutions to this. All solutions have the same logic:

    1) read a known number of characters into a buffer.
    2) if the buffer was filled, add the buffer to the result and repeat step 1.
    3) if the buffer was not filled, add the partial buffer to the result and do not repeat step 1.

    In the case of fgets, you can supply the number of characters to read. So have a small buffer, like 20 bytes. Then call fgets with the 20. If fgets reads any bytes at all it returns a non-null pointer (actually it returns the address of your buffer). At this point you could use strcat to append your buffer to the final result and then call fgets again. So put this fgets inside a loop call repeatedly call it until it returns a null pointer. At this point you have read no bytes. Either you reached the end of the record or the end of the file.

    You could replace the strcat with your own function.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      fgets assumes line termination is accomplished by a single newline character. You should confirm that is indeed the case for your input file before you use this function.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Let me add that unless you know how the file was written you won't be able to read it correcty. donbock's point is a serious one.

        Comment

        Working...