Ed Prochak
8/11/2008 4:55:00 PM
On Aug 11, 7:31 am, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
> Rajshekhar wrote:
> > Problem :
>
> > Given a text file as input, sort the lines and store in the specified
> > output file. The sorting need not make any differenciation with
> > regards to the characters (whether it is alpha / numeric /
> > alphanumeric / special). It can compare them using the ASCII value.
>
> > IMP *********** The program should not hardcode the number of lines in
> > the file in ANY manner.
>
> Remark in passing: This is too strong a condition for
> any computer with finite resources.
No it isn't. What is missing is a description of how to fail when the
limit is reached. But the limit is in the OS, not in the application
program. (E.g. think of the cp command in UNIX. it is limited by the
size of the file system, but internally it contains no such limit
value.)
[remaining good advice kept]
> The problem statement hints about using a dynamically-
> allocated memory area and expanding it if it turns out to
> be too small. Do you know how to do this? If not, review
> your notes from earlier classes or ask your teacher.
>
> One approach would be to read and store the lines[*] and
> also to maintain a dynamically-allocated array of `char*', each
> pointing to the start of a line. Each time the array fills up,
> expand it to make room for more `char*' pointers. When you've
> read all the lines, use qsort() to sort the array of `char*'
> and then write out the lines in the order indicated by the
> sorted array.
>
> [*] How do you read a line of unknown length? Same idea:
> Allocate some memory to hold its characters, then read and
> store until you've found the '\n' at the end of the line. If
> the line is too long for the memory area, expand it and keep
> on reading.
>
> --
> Eric Sosman
> esos...@ieee-dot-org.invalid
Ed