More Unix Woes

This is a discussion on More Unix Woes within the C++ Programming forums, part of the General Programming Boards category; I am writing a program that counts the number of words in a text file. How would I go about ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    12

    More Unix Woes

    I am writing a program that counts the number of words in a text file.
    How would I go about useing a command line argument as the text file name that will be opened? Right now i am opening a file in the same directory as the program.(test.txt file)

    for example: wordcount somefile.txt

    would open "somefile" and count the words in it.


    Code:
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <cctype>
    
    using namespace std;
    
    int main (int argc, char * argv[] )
    {
    
    int wordcount = 0;
    int letters = 0;
    double average = 0;
    char ch;
    	ifstream infile;
    
    	infile.open("test.txt");
    	if (infile.fail( )) 
    	{
    	cout << "Input file opening failed.\n";
    	system("pause");
    	exit(1);
    	}
    }

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    65
    Instead of "test.txt" you use argv[1]. But of course you should first check that there is a command line argument, so
    Code:
    if (argc > 1)
    {
    	infile.open(argv[1]);
    }
    else
    {
    	tell the user s/he should give a file name
    }

  3. #3
    Registered User Jaqui's Avatar
    Join Date
    Feb 2005
    Posts
    416
    to further joni's answer,

    you can also use the environment variable PATH by scanning the envp argument for the program for: "PATH="
    this means that you don't need to have the file to be opened in the same folder, without having to add any special code to have the data available, only to scan the 3rd argument to all executables "const char *argp[ ]"
    Quote Originally Posted by Jeff Henager
    If the average user can put a CD in and boot the system and follow the prompts, he can install and use Linux. If he can't do that simple task, he doesn't need to be around technology.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to program in unix
    By Cpro in forum Linux Programming
    Replies: 21
    Last Post: 02-12-2008, 09:54 AM
  2. Setting up a Unix box
    By @nthony in forum Tech Board
    Replies: 6
    Last Post: 07-22-2007, 10:22 PM
  3. UNIX (Linux, BSD, etc) Programming :: UNIX
    By kuphryn in forum Linux Programming
    Replies: 6
    Last Post: 04-01-2004, 07:44 PM
  4. Unix Sockets
    By prvindia in forum Linux Programming
    Replies: 5
    Last Post: 03-11-2003, 08:16 AM
  5. About Unix Programming - Making a career desision
    By null in forum C Programming
    Replies: 0
    Last Post: 10-14-2001, 07:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21