Command line arguments

This is a discussion on Command line arguments within the C Programming forums, part of the General Programming Boards category; I'm working on a small program that reads text file off command line and counts number of characters in it. ...

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    4

    Question Command line arguments

    I'm working on a small program that reads text file off command line and counts number of characters in it. I've created the text file placed it in the same directory as the executable. For some reason it gives me strange number in output.
    If I open the file directly through fopen (fopen("filename.txt", "r") program works corectly. But if I do something like(fopen(argv[0], "r") my program gives me strange output like 159806

    Here is the code:

    //Peter Yelagin
    //carcount.c

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char* argv[])
    {
    long n=0;
    FILE* ifp;

    ifp=fopen(*argv, "r");
    if(ifp==NULL) {perror("File not found"); exit(1);}

    fseek(ifp, n, SEEK_END);
    n=ftell(ifp);
    printf("%ld\n", n);

    fclose(ifp);

    return 0;
    }

    If you guys know what's wrong with it, please let me know.
    (I'm sure I have text file I'm trying to read in the same derectory, b/c I can open it on command prompt from that derectory).
    Thanks for your time,
    Peter

  2. #2
    Registered User
    Join Date
    Jul 2002
    Posts
    15
    Try using argv[1]. I am assuming that you use the following syntax to run your command

    <your program name> filename.txt

    argv[0] will give you the name of the executable itself. That is why you get such a huge count. the arguments you pass will start from argv[1] ...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner Needs help in Dev-C++
    By Korrupt Lawz in forum C++ Programming
    Replies: 20
    Last Post: 09-28-2010, 02:17 AM
  2. GradeInfo
    By kirksson in forum C Programming
    Replies: 23
    Last Post: 07-16-2008, 04:27 PM
  3. command line arguments
    By vurentjie in forum C Programming
    Replies: 3
    Last Post: 06-22-2008, 07:46 AM
  4. Replies: 10
    Last Post: 09-27-2005, 01:49 PM
  5. NULL arguments in a shell program
    By gregulator in forum C Programming
    Replies: 4
    Last Post: 04-15-2004, 11:48 AM

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