473,696 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A better way to tail a file

Is there a way to write a c++ program that will
print out the last few lines of a file without reading
the whole file? The implementations of 'tail' I have
seen all appear to be system dependent. I am looking for
a standard (portable) c++ solution that will do just a
fraction of tail's functionality. To make a long story short,
I am looking for suggestions that may help me improve the
speed of the following implementation for long input files:

/*
Command line utility to display the last few lines of a text file.

Usage: (1) tail <filename>
(2) tail <filename> <number of lines>

<filename> is the name of the file whose last few lines you want to
display
<number of lines> is the number of lines you want to display
(default is NumberOfLines)

Implementation note: this is an inefficient implementation that
reads the whole file
only to display a few lines from the end of the file.
*/

#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <deque>

// Forward declarations
bool writetail(const std::string & filename, long numlines);
void usage(long NumberOfLines);

int main (int argc, char** argv)
{
const long NumberOfLines = 10;
long numlines;
std::string filename;
switch (argc)
{
case 2:
filename = argv[1];
numlines = NumberOfLines;
break;
case 3:
filename = argv[1];
numlines = strtol(argv[2], NULL, 10);
if (numlines <= 0 || errno == ERANGE)
{
std::cerr << argv[0] << ": error in second command line
argument" << '\n';
usage(NumberOfL ines);
return 1;
}
break;
default:
std::cerr << argv[0] << ": missing command line arguments" <<
'\n';
usage(NumberOfL ines);
return 1;
}
bool status = writetail(filen ame, numlines);
if (!status)
{
std::cerr << argv[0] << ": execution errors" << '\n';
usage(NumberOfL ines);
return 1;
}
return 0;
}

bool writetail(const std::string & filename, long numlines)
{
std::ifstream input(filename. c_str());
if (!input)
{
std::cerr << "writehead: error opening file: " << filename <<
'\n';
return false;
}
std::string s;
std::deque<std: :string> lines;
long kount = 0;
while (std::getline(i nput, s))
{
lines.push_back (s);
++kount;
if (kount == numlines) break;
}
while (std::getline(i nput, s))
{
lines.pop_front ();
lines.push_back (s);
}
std::deque<std: :string>::itera tor p;
for (p = lines.begin(); p < lines.end(); ++p)
std::cout << *p << '\n';
input.close();
return true;
}

void usage(long NumberOfLines)
{
std::cerr << "usage: tail <filename> <number of lines (optional)>\n"
<<
" <filename> is the name of the file whose last
few lines you want to display\n" <<
" <number of lines> is the number of lines you
want to display (default is " <<
NumberOfLines << ")\n";
}
Jul 19 '05 #1
2 13041
Hi,

Look for the last modification date/time for the file. Install a timer to
read this date/time every xxx seconds or minutes
I f the modification has been changed read the file until the end is reached
i.e.

......
read file until end
fill variable lastmodified with last time file modified;
......
while(true)
{
signal SIGALRM, timerEvent );
alarm( 5 ) // every 5 seconds
}
.......

void timerEvent()
{
struct stat st;

// fd file descriptor open file
fstat( fd, &st );
if( st.st_mtime != lastmodified )
{
read file until end of file
}
lastmodified = st.st_mtime;
}
"Count Dracula" <lk**@esinet.ne t> schreef in bericht
news:fc******** *************** ***@posting.goo gle.com...
Is there a way to write a c++ program that will
print out the last few lines of a file without reading
the whole file? The implementations of 'tail' I have
seen all appear to be system dependent. I am looking for
a standard (portable) c++ solution that will do just a
fraction of tail's functionality. To make a long story short,
I am looking for suggestions that may help me improve the
speed of the following implementation for long input files:

/*
Command line utility to display the last few lines of a text file.

Usage: (1) tail <filename>
(2) tail <filename> <number of lines>

<filename> is the name of the file whose last few lines you want to
display
<number of lines> is the number of lines you want to display
(default is NumberOfLines)

Implementation note: this is an inefficient implementation that
reads the whole file
only to display a few lines from the end of the file.
*/

#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <deque>

// Forward declarations
bool writetail(const std::string & filename, long numlines);
void usage(long NumberOfLines);

int main (int argc, char** argv)
{
const long NumberOfLines = 10;
long numlines;
std::string filename;
switch (argc)
{
case 2:
filename = argv[1];
numlines = NumberOfLines;
break;
case 3:
filename = argv[1];
numlines = strtol(argv[2], NULL, 10);
if (numlines <= 0 || errno == ERANGE)
{
std::cerr << argv[0] << ": error in second command line
argument" << '\n';
usage(NumberOfL ines);
return 1;
}
break;
default:
std::cerr << argv[0] << ": missing command line arguments" <<
'\n';
usage(NumberOfL ines);
return 1;
}
bool status = writetail(filen ame, numlines);
if (!status)
{
std::cerr << argv[0] << ": execution errors" << '\n';
usage(NumberOfL ines);
return 1;
}
return 0;
}

bool writetail(const std::string & filename, long numlines)
{
std::ifstream input(filename. c_str());
if (!input)
{
std::cerr << "writehead: error opening file: " << filename <<
'\n';
return false;
}
std::string s;
std::deque<std: :string> lines;
long kount = 0;
while (std::getline(i nput, s))
{
lines.push_back (s);
++kount;
if (kount == numlines) break;
}
while (std::getline(i nput, s))
{
lines.pop_front ();
lines.push_back (s);
}
std::deque<std: :string>::itera tor p;
for (p = lines.begin(); p < lines.end(); ++p)
std::cout << *p << '\n';
input.close();
return true;
}

void usage(long NumberOfLines)
{
std::cerr << "usage: tail <filename> <number of lines (optional)>\n"
<<
" <filename> is the name of the file whose last
few lines you want to display\n" <<
" <number of lines> is the number of lines you
want to display (default is " <<
NumberOfLines << ")\n";
}

Jul 19 '05 #2
Hi,

Look for the last modification date/time for the file. Install a timer to
read this date/time every xxx seconds or minutes
I f the modification has been changed read the file until the end is reached
i.e.

......
read file until end
fill variable lastmodified with last time file modified;
......
while(true)
{
signal SIGALRM, timerEvent );
alarm( 5 ) // every 5 seconds
}
.......

void timerEvent()
{
struct stat st;

// fd file descriptor open file
fstat( fd, &st );
if( st.st_mtime != lastmodified )
{
read file until end of file
}
lastmodified = st.st_mtime;
}
"Count Dracula" <lk**@esinet.ne t> schreef in bericht
news:fc******** *************** ***@posting.goo gle.com...
Is there a way to write a c++ program that will
print out the last few lines of a file without reading
the whole file? The implementations of 'tail' I have
seen all appear to be system dependent. I am looking for
a standard (portable) c++ solution that will do just a
fraction of tail's functionality. To make a long story short,
I am looking for suggestions that may help me improve the
speed of the following implementation for long input files:

/*
Command line utility to display the last few lines of a text file.

Usage: (1) tail <filename>
(2) tail <filename> <number of lines>

<filename> is the name of the file whose last few lines you want to
display
<number of lines> is the number of lines you want to display
(default is NumberOfLines)

Implementation note: this is an inefficient implementation that
reads the whole file
only to display a few lines from the end of the file.
*/

#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <deque>

// Forward declarations
bool writetail(const std::string & filename, long numlines);
void usage(long NumberOfLines);

int main (int argc, char** argv)
{
const long NumberOfLines = 10;
long numlines;
std::string filename;
switch (argc)
{
case 2:
filename = argv[1];
numlines = NumberOfLines;
break;
case 3:
filename = argv[1];
numlines = strtol(argv[2], NULL, 10);
if (numlines <= 0 || errno == ERANGE)
{
std::cerr << argv[0] << ": error in second command line
argument" << '\n';
usage(NumberOfL ines);
return 1;
}
break;
default:
std::cerr << argv[0] << ": missing command line arguments" <<
'\n';
usage(NumberOfL ines);
return 1;
}
bool status = writetail(filen ame, numlines);
if (!status)
{
std::cerr << argv[0] << ": execution errors" << '\n';
usage(NumberOfL ines);
return 1;
}
return 0;
}

bool writetail(const std::string & filename, long numlines)
{
std::ifstream input(filename. c_str());
if (!input)
{
std::cerr << "writehead: error opening file: " << filename <<
'\n';
return false;
}
std::string s;
std::deque<std: :string> lines;
long kount = 0;
while (std::getline(i nput, s))
{
lines.push_back (s);
++kount;
if (kount == numlines) break;
}
while (std::getline(i nput, s))
{
lines.pop_front ();
lines.push_back (s);
}
std::deque<std: :string>::itera tor p;
for (p = lines.begin(); p < lines.end(); ++p)
std::cout << *p << '\n';
input.close();
return true;
}

void usage(long NumberOfLines)
{
std::cerr << "usage: tail <filename> <number of lines (optional)>\n"
<<
" <filename> is the name of the file whose last
few lines you want to display\n" <<
" <number of lines> is the number of lines you
want to display (default is " <<
NumberOfLines << ")\n";
}

Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
2507
by: Jonathan Bartlett | last post by:
Just finished a new IBM DeveloperWorks article on linked lists, and thought you all might be interested. It's not an introduction -- it instead covers some of the more interesting aspects of linked lists. http://www.ibm.com/developerworks/linux/library/l-listproc/ Jon ---- Learn to program using Linux assembly language http://www.cafeshops.com/bartlettpublish.8640017
1
1433
by: cyshao | last post by:
Are there any command like Unix "tail -f " ? I'm developing a service program who writes log file in each 5 second. Now, I want to watch changes of the contaxt of the file. I know Unix porvides such program ,"tail -f ". Does Windows has similar command?
12
4393
by: s99999999s2003 | last post by:
hi I have a file which is very large eg over 200Mb , and i am going to use python to code a "tail" command to get the last few lines of the file. What is a good algorithm for this type of task in python for very big files? Initially, i thought of reading everything into an array from the file and just get the last few elements (lines) but since it's a very big file, don't think is efficient. thanks
19
2280
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
30
4610
by: Chas Emerick | last post by:
I looked around for an ElementTree-specific mailing list, but found none -- my apologies if this is too broad a forum for this question. I've been using the lxml variant of the ElementTree API, which I understand works in much the same way (with some significant additions). In particular, it shares the use of a .tail attribute. I ran headlong into this aspect of the API while doing some DOM manipulations, and it's got me pretty...
21
8072
by: Owen Zhang | last post by:
What is the best way to implement "tail -f" in C or C++ and higher performance compared to either unix shell command "tail -f" or perl File::Tail ? Any suggestion appreciated. Thanks.
1
3065
by: cookspyder | last post by:
So I have this script and it works great at sending things over a socket after tailing a file. The problem seems to be when the recieving end is not available the program crashes. Is there a way to get the program to stay up and wait for the recieving end to be available? use File::Tail; use IO::Socket; { local $/ = "\n"; my $name = 'filename'; $file=File::Tail->new(name=> $name, maxinterval=>3, reset_tail=>0); while...
3
4536
by: sab | last post by:
Hello, I have been working on a python script to parse a continuously growing log file on a UNIX server. The input is the standard in, piped in from the log file. The application works well for the most part, but the problem is when attempting to continuously pipe information into the application via the tail -f command. The command line looks something like this: tail -f <logfile| grep <search string| python parse.py
35
4722
by: Muzammil | last post by:
int harmonic(int n) { if (n=1) { return 1; } else { return harmonic(n-1)+1/n; } } can any help me ??
0
8661
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9142
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9008
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8875
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8849
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7699
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3030
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.