Author Topic:   Changing the order of text lines
posted April 14, 2001 09:53 AM            
I have text files, several hundreds of lines each, and I need to copy each file into a new file and rearrange the lines into reverse order (first line last and vice versa).

Now what would be a fast way to do this in c/c++? I can't think of anything reasonable.

ifstream::seekg function doesn't seem to work right in MSVC 6.


posted April 14, 2001 07:30 PM         
Just a question, is this for a specific purpose?

Assuming each line has a max. length of 256 characters, you can use fgets()
to read in a entire line and allocate it to some system memory. Then after
the entire file is read, close it, and flip the lines in the allocated memory.

// determine max. num. of lines and allocate buffer here

char line_buffer[256];
while (fgets(line_buffer, 256, File) != NULL) {
// store line in allocated buffer here

// flip allocated buffer here

// create new file here

// write out lines to new file

That's how I would do it. But I guess you could also do it without
allocating memory by opening both files at the same time and copy
lines from one file to the other. But you really didn't say anything
about whether it should be fast or not.


posted April 16, 2001 03:38 PM            
I've actually tried it that way, but it was really slow (files are around 300kb). I was looking for something faster.


New Member
posted April 20, 2001 02:52 PM            
If you want it to be fast, you should allocate some memory, and read the whole file into the allocated block. fgetc() and similar functions are very slow.

Once you have read it into the memory, just search through the memory block backwards for the newline or carriage return characters (this can be 10,13 or '\n' depending on where the text file is from). Once you have found a newline or CR byte, copy that line into the start of another block of memory the same size, until you reach the end of that line. Keep on doing this until you have scanned back to the beginning of the file.