Thread: Command line arguments

  1. #1
    Registered User
    Join Date
    May 2002

    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

    #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);
    printf("%ld\n", n);


    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,

  2. #2
    Registered User
    Join Date
    Jul 2002
    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, 01:17 AM
  2. GradeInfo
    By kirksson in forum C Programming
    Replies: 23
    Last Post: 07-16-2008, 03:27 PM
  3. command line arguments
    By vurentjie in forum C Programming
    Replies: 3
    Last Post: 06-22-2008, 06:46 AM
  4. Replies: 10
    Last Post: 09-27-2005, 12:49 PM
  5. NULL arguments in a shell program
    By gregulator in forum C Programming
    Replies: 4
    Last Post: 04-15-2004, 10:48 AM