473,788 Members | 2,896 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem Outputting Command Line Arguments from argv

Hello. I'm having a very strange problem that I would like ot check
with you guys.

Basically whenever I insert the following line into my programme to
output the arguments being passed to the programme:

printf("\nComma nd line arguement %d: %s.", i , argv[i] );

The porgramme outputs 3 of the command line arguements, then gives a
segmentation fault on the next line, followed by other strange
behaviour.

Does outputting the command line arguments change them or some other
aspect of the programme somehow? The programme runs fine when I
comment the line out, which just makes no sense to me!

Kind Regards,

Matt

Jul 19 '07
17 3382
Forgot to mention, the code above should compile so feel free to give
it a try.

Jul 23 '07 #11
Matt <ma*****@hotmai l.comwrites:
[...]
I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.
I'm a little surprised it didn't compile, but using '-c' is nonsense.
Multi-character character constants have implementation-defined
values, and should be avoided. '-c' and "-c" are entirely different
things.

I think a large part of the problem is that you're trying to program
by wild guessing. You need to understand what you're doing *before*
you write or modify your code. Making random changes will most likely
cause your code to fail to compile. If by chance it still compiles,
it probably won't work. If by chance it appears to work, that's
probably just bad luck; it's *very* easy in C to write incorrect code
that happens to "work" because you got lucky with undefined behavior.

Correctly working C code is a very small target, tightly surrounded by
code that's incorrect in various subtle ways. The only way to hit the
target is to know where it is and aim at it directly.

Study your text book (K&R2 is good), decide what you want to do,
figure out how to do it, and do it.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 23 '07 #12
On Jul 24, 2:15 am, Matt <matt...@hotmai l.comwrote:
char *getopt_val;
[...]
if (getopt_val == -1)
This is an error. If you did not get a compiler
warning or error here, then you need to learn
how to invoke your compiler properly.

I can't suggest what the 'correct' code would
be, because you haven't posted any of the
code for 'getopt_long'. Perhaps you would get
better answers by posting your program on a
newsgroup where 'getopt_long' is topical
(possibly a GCC group or a Unix programming group).
switch (*getopt_val)
You should check that getopt_val is not NULL
before doing this.

Also, don't put too much stock in any debugger
report that one particular piece of code is the
problem, they often get it wrong, especially if
you haven't compiled your code to disable optimizations.
printf ("option %s", long_options[option_index].name);

if (optarg)
You haven't declared 'optarg' anywhere, as far as I can see.
Jul 24 '07 #13
On Mon, 23 Jul 2007 14:15:38 -0000, Matt <ma*****@hotmai l.comwrote:
>I have just tried running the code given from the GNU Example page,
and as I should have expected, the code was fine.

Now when I put my own implementation of this code (which is of course
very similar) by itself, I got a segmentation fault whenever I put in
an argument such as "-c" or "-stack" that the programme is meant to
recognise and act upon. The problem does not occur if I use "c" or
"stack":

// A programme to test my implementation of the getopt_long function
in an independant environment from the main programme

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

static int stack_mode = 0;

int main( int argc , char *argv[] )

{

extern int stack_mode;
Other than hiding the previous object with this name, what do you
think this accomplishes?
>
char *getopt_val;
int i;

opterr = 0;

printf("argc = %d\n",argc);

for ( i = 0 ; i < argc ; i++ )

{

printf("argv[%d] = %s\n",i,argv[i]);

}

for ( i = 0 ; i < argc ; i++ ) // argc is the number of command line
arguments passed to the programme.

{

while (1)

{

static struct option long_options[] =

{

// These options set a flag.
{"stack" , no_argument , &stack_mode , 1}, // Enable stack
(convolution ) mode

// These options don't set a flag. We distinguish them
by their indices.
{"configfile " , required_argume nt , 0 , 'c'},
{0 , 0 , 0 , 0}

};

// getopt_long stores the option index here.
int option_index = 0;

getopt_val = getopt_long (argc, argv, "c:", long_options,
&option_index) ;

// Detect the end of the options.
if (getopt_val == -1)
getopt_val was defined above as a char*. -1 is an int. You cannot
compare an int to a pointer this way. What is the real return type of
getopt_long? This statement is a constraint violation that requires a
diagnostic.
>
{

break;

}

switch (*getopt_val)

{

case 0:
/* If this option set a flag, do nothing else now. */
if ( long_options[option_index].flag != 0)

{
Judicious use of white space makes your code readable. Double spacing
nearly every statement doesn't qualify.
break;

}

printf ("option %s", long_options[option_index].name);

if (optarg)
What is optarg?
>
{

printf (" with arg %s", optarg);

}

printf ("\n");
break;

case 'c':
printf ("option -c with value `%s'\n", optarg);
break;

case '?':
/* getopt_long already printed an error message. */
break;

default:
abort ();

}

}

/* Print any remaining command line arguments (not options). */
if (optind < argc)

{

printf ("non-option ARGV-elements: ");

while (optind < argc)
What is optind?
>
{

printf ("%s ", argv[optind++]);

}

putchar ('\n');

}

}

}

I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.
It still doesn't.
Remove del for email
Jul 24 '07 #14
I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.

I'm a little surprised it didn't compile, but using '-c' is nonsense.
Multi-character character constants have implementation-defined
values, and should be avoided. '-c' and "-c" are entirely different
things.
Good point. Ta for the advice as well.

Jul 24 '07 #15
Matt <ma*****@hotmai l.comwrites:
I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.

I'm a little surprised it didn't compile, but using '-c' is nonsense.
Multi-character character constants have implementation-defined
values, and should be avoided. '-c' and "-c" are entirely different
things.

Good point. Ta for the advice as well.
I wrote the paragraph starting with "I'm a little surprised it didn't
compile ...".

Once again, please stop snipping attribution lines. You can see a
line at the top of the article "Matt <ma*****@hotmai l.comwrites:".
There was a similar line above what I wrote in your followup, but you
deleted it. Delete whatever quoted material isn't relevant to your
followup, but if you quote anything by an author, *leave the
attribution line in place*.

Not only is it simply polite to give credit (or blame) for anything
that you quote, it makes the conversation easier to follow.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 24 '07 #16
On Jul 24, 7:31 pm, Keith Thompson <ks...@mib.orgw rote:
Matt <matt...@hotmai l.comwrites:
I have tried replacing "case 'c':" with "case '-c':" and so forth in
the case statements starting on line 92, but the source code would not
compile.
I'm a little surprised it didn't compile, but using '-c' is nonsense.
Multi-character character constants have implementation-defined
values, and should be avoided. '-c' and "-c" are entirely different
things.
Good point. Ta for the advice as well.

I wrote the paragraph starting with "I'm a little surprised it didn't
compile ...".

Once again, please stop snipping attribution lines. You can see a
line at the top of the article "Matt <matt...@hotmai l.comwrites:".
There was a similar line above what I wrote in your followup, but you
deleted it. Delete whatever quoted material isn't relevant to your
followup, but if you quote anything by an author, *leave the
attribution line in place*.

Not only is it simply polite to give credit (or blame) for anything
that you quote, it makes the conversation easier to follow.

--
Keith Thompson (The_Other_Keit h) ks...@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
No problem

Jul 25 '07 #17
Matt <ma*****@hotmai l.comwrites:
On Jul 24, 7:31 pm, Keith Thompson <ks...@mib.orgw rote:
[...]
> Delete whatever quoted material isn't relevant to your
followup, but if you quote anything by an author, *leave the
attribution line in place*.
[snip]
>
No problem
Thanks, but please re-read the above. Don't quote signatures unless
you're actually commenting on them. Don't quote an entire article
unless you're commenting on everything that was said (or it's short).
Include just enough context so your followup makes sense to someone
who didn't see the parent article, no more, no less.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 26 '07 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
388
by: Ashe Corven | last post by:
i need help pretty bad for this from the command line >csend string1 4233 "string2" how can i copy string1, or string2 to a char* or a string. for argument 4 (string2)
7
2321
by: qazmlp | last post by:
void func() { // Is it by anyway possible to read the value of the first command line parameter i.e. argv here ? } int main() { func() ; // No command line arguments are passed to func(). }
2
5683
by: Julian | last post by:
I would like to have output from my program to be written to cout as well as a file. (actually, i want several other output options but this should explain my problem in the simplest way). I have seen commercial programs print output to the screen as well as to a log file. depending on the user and other situations, i might want to turn off one of the outputs or maybe even both outputs. so, i want a single line with operator << function...
2
4202
by: SunRise | last post by:
Hi I am creating a C Program , to extract only-Printable-characters from a file ( any type of file) and display them. OS: Windows-XP Ple help me to fix the Errors & Warnings and explain how to use Command-Line Arguments inside C program.
13
2811
by: Sree | last post by:
If the program (myprog) is run from the command line as myprog 1 2 3 , What would be the output? main(int argc, char *argv) { int i; for(i=0;i<argc;i++) printf("%s",argv); }
40
2750
by: raphfrk | last post by:
I have a program which reads in 3 filenames from the command line prog filename1 filename2 filename3 However, it doesn't work when one of the filenames has spaces in it (due to a directory name with a space in it) because that filename gets split into 2. I tried
16
2724
by: John Salerno | last post by:
Here's my new project: I want to write a little script that I can type at the terminal like this: $ scriptname package1 where scriptname is my module name and any subsequent arguments are the names of Linux packages to install. Running the script as above will create this line: sudo aptitude install package1 package2 ...
0
2029
by: raa abdullah | last post by:
Overview A conflict-serializbility\recoverability checker, SCR, is a program that takes in a schedule and outputs 2 decisions: Conflict serialzable or Not confilict serializable AND Recoverable or Not recoverable. The following is a detailed description of the program. Input The input to SCR should be a schedule of operations. It should be in a text file (.txt) where each line is in the following format: Operation TransactionNum ...
4
2993
by: neha_chhatre | last post by:
please let me know if am using command line arguments, how to send arguments to a C program if i am working on ubuntu say for example suppose name of my program is prog.c if argc=3 then how to send those three arguments(pt1.txt,pt2.txt,pt3.txt) to prog.c through command prompt if i am working on linux
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.