Reading lines from a file in C
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 :
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
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...
you don't have to read variable length lines: simply read the files in fixed sized chunks, say 1024 chars at a time.
Last Post: 02-20-2010, 04:17 AM
By Jenks in forum VB Classic
Last Post: 05-24-2005, 03:22 PM
Last Post: 11-14-2001, 01:49 PM
By Cynthia Leslie in forum Java
Last Post: 06-09-2001, 07:43 PM
By Millard Melnyk in forum VB Classic
Last Post: 06-02-2000, 01:13 PM
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center