Thread: reading from argv[]

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    24

    reading from argv[]

    Hey does anyone have any clue why filename is never getting allocated in the code below?
    I read it afterwards and its giving me a seg fault.
    Code:
    for (i = 1; i < (argc + 1); i++){
    			if (strcmp(argv[i], "-h") == 0){ /* -h operand is in command line */
    				isHtml = 1; 
    			}	
    			else if (strcmp(argv[i], "-f") == 0){
    				hasFilter = 1;
    				if (argv[i + 1] != NULL){
    					filterfile = argv[++i];
    				}
    				else{
    					fprintf(stderr, "Usage: tvprogs [-h] [-f filterfile] epgXMLfile");
    					return EXIT_FAILURE;
    				}
    			}
    			else {
    				filename = argv[i];
    			}
    		}

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    For starters, your loop is wrong. You should be stopping at less than argc, not less than or equal to. Next, you can't copy strings using the assignment operator. Look into strcpy.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Apr 2009
    Posts
    24
    Ok changed those two, still getting a seg fault though
    Code:
    for (i = 1; i < argc; i++){
    .
    .
    .
    else{
    					fprintf(stderr, "Usage: tvprogs [-h] [-f filterfile] epgXMLfile");
    					return EXIT_FAILURE;
    				}

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    24
    sorry I meant
    Code:
    else {
    				strcpy(filename, argv[i]);
    			}

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Your code sample doesn't actually help us here, since it doesn't show us anything you're actually doing, other than printing an error. Try making a small compilable program, with just you reading through the arguments, printing them. Then try copying them to an array, and printing that.


    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Registered User
    Join Date
    Apr 2009
    Posts
    24
    alright thanks quzah I'll try that

  7. #7
    Registered User
    Join Date
    Apr 2009
    Location
    Russia
    Posts
    116
    Code:
            strcpy(filename, argv[i]);
    filename must be an array of chars

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading a file
    By nhubred in forum C++ Programming
    Replies: 3
    Last Post: 05-21-2009, 11:34 AM
  2. Replies: 3
    Last Post: 03-05-2009, 03:14 AM
  3. Replies: 7
    Last Post: 02-02-2009, 07:27 AM
  4. Replies: 2
    Last Post: 01-28-2008, 03:07 AM
  5. void main(), int main(), argc, argv[]????
    By Jonny M in forum C Programming
    Replies: 3
    Last Post: 03-06-2002, 09:12 AM