Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Monday, December 3, 2012

Print out the size of the file In c++

In this Programm, given the name of a file, print out the size of the file, in bytes. If no file is given, provide a help string to the user that indicates how to use the program. You might need help with taking parameters via the command line or file I/O in C++

This solution uses some sophisticated features of ifstream, but it can be done by simple counting bytes as well.



/*
 * This program was created by Denis Meyer 
 * Gugzi said,,No Plagiarism :P 
 */
#include <iostream>
#include <fstream>
using namespace std;

int main (int argc, char* const argv[]) {
        if ( argc < 1 )
        {
                cout << endl << "Usage programname filename" << endl << endl;
                return 1;
        }
        else if ( argc != 2 )
        {
                cout << endl << "Usage: " << argv[0] << " filename" << endl << endl;
                return 1;
        }
    
    ifstream file(argv[1]);
    if(!file.is_open()) {
        cout << endl << "Couldn't open File " << argv[1] << endl << endl;
        return 1;
    }
    
    long begin, end;
    
    begin = file.tellg();
    file.seekg (0, ios::end);
    end = file.tellg();
    
    file.close();
    
    cout << endl << "The Size of the File '" << argv[1] << "' is: " << (end-begin) << " Byte." << endl << endl;
    
    return 0;
}

Counts the total number of lines in a file using strcut c++

Here's a simple help  to get you started with struct: write a program that takes a file as an argument and counts the total number of lines. Lines are defined as ending with a newline character. Program usage should be
count filename.txt
and the output should be the line count.
#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
 if(argc!=2)
 {
  cout<<"Input should be of the form 'count filename.txt'";
  return 1;
 }
 else
 {
  ifstream input_file(argv[1]);
  if(!input_file)
  {
   cout<<"File "<<argv[1]<<" does not exist";
   return 0;
  }
  char c;
  int count = 0;
  while(input_file.get(c))
  {
   if(c == '\n')
   {
    count++;
   }
  }
  cout<<"Total lines in file: "<<count;
 }
 return 0;
}
Many other solutions exist! If yours doesn't match the Learn4Develop key, but it still works, let me know and I'll upload it as an alternative answer.