Thread: File I/O

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    15

    File I/O

    Heh, stumped by something easy again.

    What's the C++ equivilant of the DOS command "type"?

    I know some basic file i/o but this is a little beyond me.

    Allow me to elaborate a little:

    I've got a bunch of files, they all contain 2 lines. I'd like to be able to (on command) display their contents.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    1. You need to open the file for reading (use an ifstream object)
    2. You need to read the lines of data from the file (use the stream extraction operator (>>) or get/getline function calls to read into an appropriate buffer or string container)
    3. You need to display the data just read to the console (write the data read to cout most likely)
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    TYPE is boring, let's do Unix's cat instead:
    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char **parse_options ( char *argv[] );
    void read_file ( FILE *in );
    void version ( void );
    void help ( void );
    
    #define BLANK_LINES 1
    #define ALL_LINES   2
    
    static int control;    /* Show control characters as ^ */
    static int show_count; /* Show line count */
    static int show_end;   /* End lines with $ */
    static int show_tab;   /* Show tabs as ^I */
    static int squeeze;    /* Change multiple blank lines into one */
    
    static int line = 1;
    
    int main ( int argc, char *argv[] )
    {
      argv = parse_options ( argv );
    
      if ( *argv == NULL )
        read_file ( stdin );
      else {
        FILE *in;
    
        for ( ; *argv != NULL; *++argv ) {
          if ( **argv == '-' )
            in = stdin;
          else {
            if ( ( in = fopen ( *argv, "r" ) ) == NULL )
              continue;
          }
    
          read_file ( in );
        }
      }
    
      return 0;
    }
    
    char **parse_options ( char *argv[] )
    {
      while ( *++argv != NULL && **argv == '-' ) {
        /* Terminating options */
        if ( strcmp ( *argv, "--version" ) == 0 )
          version();
        if ( strcmp ( *argv, "--help" ) == 0 )
          help();
    
        /* Behavioral switches */
        while ( *++(*argv) != '\0' ) {
          switch ( **argv ) {
          case 'b': show_count = BLANK_LINES;          break;
          case 'e': control = show_end = 1;            break;
          case 'n': show_count = ALL_LINES;            break;
          case 's': squeeze = 1;                       break;
          case 't': control = show_tab = 1;            break;
          case 'u': /* No-op for Unix compatibility */ break;
          case 'v': control = 1;                       break;
          case 'A': control = show_end = show_tab = 1; break;
          case 'E': show_end = 1;                      break;
          case 'T': show_tab = 1;                      break;
          default: /* Ignore unrecognized switches */  break;
          }
        }
      }
    
      return argv;
    }
    
    void read_file ( FILE *in )
    {
      int ch, last;
    
      for ( last = '\n'; ( ch = getc ( in ) ) != EOF; last = ch ) {
        if ( last == '\n' ) {
    line_count:
          if ( show_count == ALL_LINES )
            printf ( "%-5d", line++ );
          else if ( show_count == BLANK_LINES && ch != '\n' )
            printf ( "%-5d", line++ );
    
          if ( squeeze && ch == '\n' ) {
            if ( show_end )
              putchar ( '$' );
            putchar ( '\n' );
    
            /* Ignore extra empty lines */
            while ( ( ch = getc ( in ) ) != EOF && ch == '\n' )
              ;
    
            if ( ch == EOF )
              break;
            else
              goto line_count; /* Print line # first */
          }
        }
    
        if ( show_tab && ch == '\t' )
          printf ( "^I" );
        else if ( control && iscntrl ( ch ) )
          putchar ( '^' );
        else if ( show_end && ch == '\n' )
          printf ( "$\n" );
        else
          putchar ( ch );
      }
    }
    
    void version ( void )
    {
      printf ( "cat clone v1.0\n" );
      exit ( EXIT_SUCCESS );
    }
    
    void help ( void )
    {
      printf ( "cat [-benstuvAET] [--help] [--version] [file...]\n" );
      exit ( EXIT_SUCCESS );
    }
    Of course, that's C. I just grabbed something lying around on my hard drive. A conversion to C++ using iostreams is fairly trivial:
    Code:
    #include <cctype>
    #include <cstdlib>
    #include <cstring>
    #include <fstream>
    #include <iomanip>
    #include <iostream>
    #include <limits>
    
    namespace {
      const int BLANK_LINES = 1;
      const int ALL_LINES = 2;
    
      int control;    /* Show control characters as ^ */
      int show_count; /* Show line count */
      int show_end;   /* End lines with $ */
      int show_tab;   /* Show tabs as ^I */
      int squeeze;    /* Change multiple blank lines into one */
    
      int line = 1;
    
      char **parse_options ( char *argv[] );
      void read_file ( std::istream& in );
      void version ( void );
      void help ( void );
    }
    
    int main ( int argc, char *argv[] )
    {
      argv = parse_options ( argv );
    
      if ( *argv == 0 )
        read_file ( std::cin );
      else {
        std::ifstream in;
    
        for ( ; *argv != NULL; *++argv ) {
          if ( **argv == '-' )
            read_file ( std::cin );
          else {
            in.open ( *argv );
    
            if ( !in )
              continue;
    
            read_file ( in );
          }
        }
      }
    }
    
    namespace {
      char **parse_options ( char *argv[] )
      {
        while ( *++argv != NULL && **argv == '-' ) {
          /* Terminating options */
          if ( std::strcmp ( *argv, "--version" ) == 0 )
            version();
          if ( std::strcmp ( *argv, "--help" ) == 0 )
            help();
    
          /* Behavioral switches */
          while ( *++(*argv) != '\0' ) {
            switch ( **argv ) {
            case 'b': show_count = BLANK_LINES;          break;
            case 'e': control = show_end = 1;            break;
            case 'n': show_count = ALL_LINES;            break;
            case 's': squeeze = 1;                       break;
            case 't': control = show_tab = 1;            break;
            case 'u': /* No-op for Unix compatibility */ break;
            case 'v': control = 1;                       break;
            case 'A': control = show_end = show_tab = 1; break;
            case 'E': show_end = 1;                      break;
            case 'T': show_tab = 1;                      break;
            default: /* Ignore unrecognized switches */  break;
            }
          }
        }
    
        return argv;
      }
    
      void read_file ( std::istream& in )
      {
        char ch, last;
    
        for ( last = '\n'; in.get ( ch ); last = ch ) {
          if ( last == '\n' ) {
    line_count:
            if ( show_count == ALL_LINES )
              std::cout<< std::left << std::setw ( 5 ) << line++;
            else if ( show_count == BLANK_LINES && ch != '\n' )
              std::cout<< std::left << std::setw ( 5 ) << line++;
    
            if ( squeeze && ch == '\n' ) {
              if ( show_end )
                std::cout.put ( '$' );
              std::cout.put ( '\n' );
    
              /* Ignore extra empty lines */
              in.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
    
              if ( in.eof() )
                break;
              else
                goto line_count; /* Print line # first */
            }
          }
    
          if ( show_tab && ch == '\t' )
            std::cout<<"^I";
          else if ( control && std::iscntrl ( ch ) )
            std::cout<<'^';
          else if ( show_end && ch == '\n' )
            std::cout<<"$\n";
          else
            std::cout.put ( ch );
        }
      }
    
      void version ( void )
      {
        std::cout<<"cat clone v1.0\n";
        std::exit ( EXIT_SUCCESS );
      }
    
      void help ( void )
      {
        std::cout<<"cat [-benstuvAET] [--help] [--version] [file...]\n";
        std::exit ( EXIT_SUCCESS );
      }
    }
    It compiles and links cleanly, but I haven't tested the C++ version. So if it doesn't work, you're on your own.
    My best code is written with the delete key.

  4. #4
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    code looks good. this is the only questionable thing I see:

    Code:
    if ( in.eof() )

    :P
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >this is the only questionable thing I see
    Maybe it's because I wrote the code and can't seem my own flaws, but what's questionable about it? Aside from using !in instead to also cover for input errors.
    My best code is written with the delete key.

  6. #6
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    I also see a goto
    Woop?

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I also see a goto
    I'm a rebel like that.
    My best code is written with the delete key.

  8. #8
    Registered User
    Join Date
    Apr 2005
    Posts
    15
    I appreciate the help. What you guys have is a little hard for me to decipher. (I am still very new to programming.) I think what I was looking for was something like this:
    Code:
    void filename(){
         char filecontents;
         ifstream filename("filename");
         while(filename.get(filecontents)){
                      cout << filecontents; }
         }
    BTW- I didn't know goto worked in C++ like it does with batch. Go figure.
    Last edited by bliss; 06-29-2005 at 06:53 PM.

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I think what I was looking for was something like this
    If you pulled that out of the mess that I posted, you have a bright future ahead of you in the field of programming.

    >I didn't know goto worked in C++ like it does with batch.
    Goto works the same everywhere, except where it doesn't.
    My best code is written with the delete key.

  10. #10
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    also, this doesn't really do anything:
    Code:
            if ( !in )
              continue;
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Quote Originally Posted by The Brain
    also, this doesn't really do anything:
    Code:
            if ( !in )
              continue;
    As I said, I did the conversion in a hurry, didn't test it, and any mistakes are your problem.
    My best code is written with the delete key.

  12. #12
    Registered User
    Join Date
    Apr 2005
    Posts
    15
    Quote Originally Posted by Prelude
    >I think what I was looking for was something like this
    If you pulled that out of the mess that I posted, you have a bright future ahead of you in the field of programming.

    >I didn't know goto worked in C++ like it does with batch.
    Goto works the same everywhere, except where it doesn't.



    I wish I could've pulled that out of what you posted. A lot of that didn't make a lot of sense, ah well, I'm learnin' at least.
    Last edited by bliss; 06-30-2005 at 03:40 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  3. 2 questions surrounding an I/O file
    By Guti14 in forum C Programming
    Replies: 2
    Last Post: 08-30-2004, 11:21 PM
  4. File I/O problems!!! Help!!!
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 05-17-2002, 08:09 PM
  5. advice on file i/o
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-29-2001, 05:56 AM