-
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
Regards
Tapajyoti
-
Hi,
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...
Regards,
D
D
-
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
-
Replies: 4
Last Post: 02-20-2010, 04:17 AM
-
By Jenks in forum VB Classic
Replies: 6
Last Post: 05-24-2005, 02:22 PM
-
Replies: 2
Last Post: 11-14-2001, 01:49 PM
-
By Cynthia Leslie in forum Java
Replies: 3
Last Post: 06-09-2001, 06:43 PM
-
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
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|