Reading lines from a file in C

DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Reading lines from a file in C

  1. #1
    Join Date
    Jan 2005

    Reading lines from a file in C

    Hello everyone,

    I am reading lines from a simple text file in C. But the problem I am facing is the lines are of variable length, say for example the shortest one is of length 5 while the largest one is almost 100000 characters long.I am reading the files in the standard way :

    char line[100000];

    fgets( line, sizeof(line), filepointer );

    Now the problem is in this way I am wasting a lot of memory unnesecarily, but even if I use malloc() I'll have to call for a certain number of bytes so that would be wasteful too for shorter lines.

    Is there any better way for doing this?

    Thanks in advance



  2. #2
    Join Date
    Jan 2005
    it might sound daft, but why don't you just iterate through the file until you find your line delimiter (char(10) or char(13) or char(10)/char(13) combi) and then allocate exactly the amount of memory you need? You are talking about roughly 100k long lines here which should be no problem on any computer nowadays, but if you are concerned, you could try to read your lines in smaller chunks (say 1k) and build them up by strcat'ing? If you used C++ there would be slighly more elegant ways to do that, though...




  3. #3
    Join Date
    Nov 2003
    you don't have to read variable length lines: simply read the files in fixed sized chunks, say 1024 chars at a time.
    Danny Kalev

Similar Threads

  1. Replies: 4
    Last Post: 02-20-2010, 03:17 AM
  2. Reading and writing lines from a text file...
    By Jenks in forum VB Classic
    Replies: 6
    Last Post: 05-24-2005, 02:22 PM
  3. Replies: 2
    Last Post: 11-14-2001, 12:49 PM
  4. How to use Java to lock a file
    By Cynthia Leslie in forum Java
    Replies: 3
    Last Post: 06-09-2001, 06:43 PM
  5. Reading file properties
    By Millard Melnyk in forum VB Classic
    Replies: 0
    Last Post: 06-02-2000, 12:13 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
Latest Articles
Questions? Contact us.
Web Development
Latest Tips
Open Source

   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center