Remove x number of lines from beginning of file

Steve smorrey at gmail.com
Thu Oct 25 22:47:42 MDT 2007


This code is much improved...

:~$ g++ -O3 fronicate.cpp -o fronicate
:~$ time ./fronicate test.file 5

real    0m0.006s
user    0m0.004s
sys     0m0.000s

ANyways here is my second shot at it...

#include <iostream>
#include <fstream>


int main(int argc, char* argv[]){
	if(argc > 2){
		std::string filename = argv[1];
		int skiplines = atoi(argv[2]);
		std::fstream file (filename.c_str());
		std::string filestr;
		int pos = 0;
		
		if(file.is_open()){
			
			// determine length of file:
			file.seekg (0, std::ios::end);
			int length = file.tellg();

			//rewind
			file.seekg (0, std::ios::beg);

			// allocate memory:
			char* buffer = new char [length];

			// slurp the file
			file.read (buffer,length);
			
			//rewind
			file.seekg (0, std::ios::beg);
			
			//copy the buffer into the filestr
			filestr = buffer;
			
			//delete the buffer
			delete[] buffer;

			//Find all newline occurances up to skiplines
			for(int x=1; x < skiplines;x++){
				pos = filestr.find("\n",pos);
				pos++;
			}
			
			//write data back to file
			file << filestr.substr(pos,std::string::npos);
			
			//back pad missing bytes
			for(int x= 0; x < pos; x++)
				file << " ";
			
			file.close();
		}

		}else{
		std::cout << "fronicate is a program intended to truncate a given
number of lines from the front of a file" << std::endl;
		std::cout << "Usage: truncate FILENAME LINES" << std::endl;
	}
	
}


Note:  I realize this could probably be optimized further, especially
in the places where I'm calling loops, also the code probably has some
bug or two in it somewhere.  And since the application only runs once,
then exits, we could probably get away with not deleting the buffer.

But I'm out of time on this.  Enjoy!

On 10/25/07, Steve <smorrey at gmail.com> wrote:
> It could definitely be optimized.
> Slurping the entire file, skipping x newlines and rewriting the file
> in one swoop would probably be significantly faster.
> However the point was to show a different approach than simply nicing
> the existing process, or utilizing an existing utilty.
>
> Just curious Dave, but what command did you use to compile?  I used
> the O3 flag and got a time that was slightly better than before on my
> real time.
>
> Sincerely,
> Steve
>
> On 10/25/07, Dave Smith <dave at thesmithfam.org> wrote:
> > Steve wrote:
> > > Anyways back to the subject, I whipped up a little program that should
> > > do the trick.
> >
> > If sed was bad, I guess I don't see how this is better because it uses
> > the same approach, and it's slower in my testing.
> >
> > --Dave
> >
> > /*
> > PLUG: http://plug.org, #utah on irc.freenode.net
> > Unsubscribe: http://plug.org/mailman/options/plug
> > Don't fear the penguin.
> > */
> >
>



More information about the PLUG mailing list