Thread: Text program
View Single Post
Old 10-25-2004, 07:07 AM   #4 (permalink)
redhead
Newbie
 
redhead's Avatar
 
Join Date: Jun 2002
Location: Denmark
Posts: 1,735
redhead is on a distinguished road
something like this?
Code:
#include <iostream>
#include <fstream>
#include <string>

using std::cout;
using std::endl;

const int line_length = 200;

int main(int argv, char* argc[])
{
  char buffer[line_length];
  if(argv != 2)
    {
      cout << "Usage: " << argc[0] << " <filename>" << endl;
      return -1;
    }

  ifstream file (argc[1], ios::in);
  if (!file.is_open())
    {
      cout << "Error: opening file " << argc[1] << endl;
      return -1;
    }
  while (!file.eof() )
    {
      file.getline(buffer, line_length -1);
      strtok(buffer, ":");
      cout << buffer << endl;
    }
  file.close();
  return 0;
}
The use of strtok() should be thought through, since what I use it for here is using it's bad sideeffect for a good thing(tm).
strtok() changes it's first argument uppon first call, this will result in whatever is placed befor the : will remain in buffer, for a better usage, you'd probaly change it to:
Code:
int main(int argv, char* argc[])
{
  char buffer[line_length];
  char *ptr;
  if(argv != 2)
...
  while (!file.eof() )
    {
      file.getline(buffer, line_length -1);
      ptr = strtok(buffer, ":");
      cout << ptr << endl;
...
In this way you can make a check to see if it's a valid token found by strtok().

If you want it to show the port aswell, but seperated from the IP number, this might be useful:
Code:
...
  while (!file.eof() )
    {
      file.getline(buffer, line_length -1);
      ptr = strtok(buffer, ":");
      while(ptr != NULL)
        {
          cout << ptr << endl;
          ptr = strtok(NULL, "\t :");
        }
    }
...
This will also make a <tab> or <space> delimited file readable.
__________________
Don't worry Ma'am, We're university students, We know what We're doing.
-----
If you pull the pin, Mr.Grenade would no longer be your friend.
-----
01000111 01101111 00100000 01000011 00100000 00100001

Last edited by redhead; 10-25-2004 at 07:36 AM.
redhead is offline   Reply With Quote