Sponsored Content
Top Forums Programming unable to send a char parameter from main to a function Post 302564364 by Corona688 on Thursday 13th of October 2011 12:58:38 PM
Old 10-13-2011
I think you're very confused about variables, assignments, and return values, not just how getopt works. I continue to suspect the existence of latent bugs in your treewalker function, whether it works for you right now or not. Please post your entire code, not just the bits you think I need to know.

Your 'dir', 'file', and 'slink' variables are useless, you already know what 'c' is.

You shouldn't be setting optarg, you should be using optarg.

I still cannot fathom the purpose of your getFileMode function. You just return the same value you get, after setting a local variable, which changes nothing outside the function. What is it supposed to be doing?

Code:
switch (c) {
        case 't':
            // c isn't an ASCII 0, it's an ascii NULL.  If you want it to print 0,
            // initialize c to c='0' at the start of main.
            printf("Type is  set to: %c\n", charSetter); /*should be zero*/

            // the option string appears in optarg.
            printf("option:  %s\n", optarg);
            break;
            
        case 'd':
        case 'f':
        case 'l':
            charSetter=c;
            printf("%c is set\n", charSetter);
            break;
        default:
            fprintf(stderr, "Uknown option\n");
            exit(1);
        }

---------- Post updated at 10:58 AM ---------- Previous update was at 10:55 AM ----------

If your variables were an attempt to organize it, I think enums are closer to what you want. They even work in switch statements.

Code:
enum
{
        TYPE_DIR='d',
        TYPE_FILE='f', 
        TYPE_SLINK='l',
        TYPE_T='t',
};

...

switch (c) {
        case TYPE_T:
            // c isn't an ASCII 0, it's an ascii NULL.  If you want it to print 0,
            // initialize c to c='0' at the start of main.
            printf("Type is  set to: %c\n", charSetter); /*should be zero*/

            // the option string appears in optarg.
            printf("option:  %s\n", optarg);
            break;
            
        case TYPE_DIR:
        case TYPE_FILE:
        case TYPE_SLINK:
            charSetter=c;
            printf("%c is set\n", charSetter);
            break;
        default:
            fprintf(stderr, "Uknown option\n");
            exit(1);
        }

 

10 More Discussions You Might Find Interesting

1. Programming

c++ calling main() function

i just finished a project for a c++ class that i wrote at home on my computer, compiled with gcc. when i brought the code into school it would not compile, it would complain that cannot call main() function. at school we use ancient borland c++ from 1995. anyway my program has 20 different... (3 Replies)
Discussion started by: norsk hedensk
3 Replies

2. Programming

main function

Is it possible to execute any function before main() function in C or C++. (6 Replies)
Discussion started by: arun.viswanath
6 Replies

3. Programming

signal handling while in a function other than main

Hi, I have a main loop which calls a sub loop, which finally returns to the main loop itself. The main loop runs when a flag is set. Now, I have a signal handler for SIGINT, which resets the flag and thus stops the main loop. Suppose I send SIGINT while the program is in subloop, I get an error... (1 Reply)
Discussion started by: Theju
1 Replies

4. Shell Programming and Scripting

Help in separating variables declared in the main function

Hi! I've a C program as shown below.. The line numbers and the statements of the program are separated by a space.. 1 #include<stdio.h> 2 char a,b,c; 3 float x,y,z; 4 int main() 5 { 6 int d,e,f; 7 // further declarations 8 // further declarations 9 /* body*/ 10 } 11 void fun1() 12... (1 Reply)
Discussion started by: abk07
1 Replies

5. Programming

How to access argv[x] from another function other than main???

Hi friends, when I am passing arguments to main, I want another function to be able to have access to that function, the problem is that I am creating athread, which has a function like void *xyz(void *), how can pass the refernce of argv to this function, if you see my program, you will better... (2 Replies)
Discussion started by: gabam
2 Replies

6. Programming

Function main returning int?

H friends, As we know, a function returns a value and that value is saved somwhere. like int Sum( int x, int y ) { return x + y; } Total = Sum( 10, 20 ); The value 30 is saved in variable Total. Now the question is, what int value does the function main return, and where is it... (5 Replies)
Discussion started by: gabam
5 Replies

7. AIX

Calling functions from main program from dlopened library function

Hello All, I am trying to call a function from the calling main program from a dlopened library function, below is the entire code, when I execute it it crashes with sigill. Can you guys help me out I guess I am missing out on the linker flag or something here. besides I am new to AIX and... (1 Reply)
Discussion started by: syedtoah
1 Replies

8. UNIX for Dummies Questions & Answers

[ksh93+] Array fed by function is empty when used in main.

I feel that i am missing something obvious but i can't find what is wrong. I have a script that is launching some functions with "&" and each call is feeding the array with a value. When all calls are finished I just want to retrieve the values of that array. It is looking like that : ... (5 Replies)
Discussion started by: bibou25
5 Replies

9. Programming

A single statement without main function in c

A sample.c file is written with only one single statement. main; Segmentation fault occurred when executed that file. Any statement other than main; is written, for example unix; then it won't compile. why is this behaviour ! (2 Replies)
Discussion started by: techmonk
2 Replies

10. UNIX for Beginners Questions & Answers

A function that refuses to run anywhere else but main()

Hi. I have some code, that for some reason, I could not post it here in this post. Here's the address for it: #if 0 shc Version 4.0.1, Generic Shell Script Compiler GNU GPL Version 3 Md - Pastebin.com First off, I used "shc" to convert the code from shell script to C. And The... (6 Replies)
Discussion started by: ignatius
6 Replies
getopt(3C)						   Standard C Library Functions 						getopt(3C)

NAME
getopt - command option parsing SYNOPSIS
SVID3, XPG3 #include <stdio.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; POSIX.2, XPG4, SUS, SUSv2 #include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; DESCRIPTION
The getopt() function is a command line parser that can be used by applications that follow Basic Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 which parallel those defined by application portability standards (see intro(1)). It can also be used by applications which addi- tionally follow the Command Line Interface Paradigm (CLIP) syntax extension guidelines 15, 16, and 17. It partially enforces guideline 18 by requiring that every option has a short-name, but it allows multiple long-names to be associated with an option. The remaining guide- lines are not addressed by getopt() and are the responsibility of the application. The argc and argv arguments are the argument count and argument array as passed to main (see exec(2)). The optstring argument specifies the acceptable options. For utilities wanting to conform to the Basic Utility Syntax Guidelines, optstring is a string of recognized option characters. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. If a character is followed by a colon (:), the option is expected to have an option-argument, which can be separated from it by white space. Utilities wanting to conform to the extended CLIP guidelines can specifiy long-option equivalents to short options by following the short-option character (and optional colon) with a sequence of strings, each enclosed in parentheses, that specify the long-option aliases. The getopt() function returns the short-option character in optstring that corresponds to the next option found in argv. The getopt() function places in optind the argv index of the next argument to be processed. The optind variable is external and is initial- ized to 1 before the first call to getopt(). The getopt() function sets the variable optarg to point to the start of the option-argument as follows: o If the option is a short option and that character is the last character in the argument, then optarg contains the next element of argv, and optind is incremented by 2. o If the option is a short option and that character is not the last character in the argument, then optarg points to the string follow- ing the option character in that argument, and optind is incremented by 1. o If the option is a long option and the character equals is not found in the argument, then optarg contains the next element of argv, and optind is incremented by 2. o If the option is a long option and the character equals is found in the argument, then optarg points to the string following the equals character in that argument and optind is incremented by 1. In all cases, if the resulting value of optind is not less than argc, this indicates a missing option-argument and getopt() returns an error indication. When all options have been processed (that is, up to the first operand), getopt() returns -1. The special option "--" (two hyphens) can be used to delimit the end of the options; when it is encountered, -1 is returned and "--" is skipped. This is useful in delimiting non-option arguments that begin with "-" (hyphen). If getopt() encounters a short-option character or a long-option string not described in the opstring argument, it returns the question- mark (?) character. If it detects a missing option-argument, it also returns the question-mark (?) character, unless the first character of the optstring argument was a colon (:), in which case getopt() returns the colon (:) character. For short options, getopt() sets the vari- able optopt to the option character that caused the error. For long options, optopt is set to the hyphen (-) character and the failing long option can be identified through argv[optind-1]. If the application has not set the variable opterr to 0 and the first character of opt- string is not a colon (:), getopt() also prints a diagnostic message to stderr. RETURN VALUES
The getopt() function returns the short-option character associated with the option recognized. A colon (:) is returned if getopt() detects a missing argument and the first character of optstring was a colon (:). A question mark (?) is returned if getopt() encounters an option not specified in optstring or detects a missing argument and the first character of optstring was not a colon (:). Otherwise, getopt() returns -1 when all command line options are parsed. ERRORS
No errors are defined. EXAMPLES
Example 1: Parsing Command Line Options The following code fragment shows how you might process the arguments for a utility that can take the mutually-exclusive options a and b and the options f and o, both of which require arguments: #include <unistd.h> int main(int argc, char *argv[ ]) { int c; int bflg, aflg, errflg; char *ifile; char *ofile; extern char *optarg; extern int optind, optopt; . . . while ((c = getopt(argc, argv, ":abf:o:")) != -1) { switch(c) { case 'a': if (bflg) errflg++; else aflg++; break; case 'b': if (aflg) errflg++; else { bflg++; bproc(); } break; case 'f': ifile = optarg; break; case 'o': ofile = optarg; break; case ':': /* -f or -o without operand */ fprintf(stderr, "Option -%c requires an operand ", optopt); errflg++; break; case '?': fprintf(stderr, "Unrecognized option: -%c ", optopt); errflg++; } } if (errflg) { fprintf(stderr, "usage: . . . "); exit(2); } for ( ; optind < argc; optind++) { if (access(argv[optind], R_OK)) { . . . } This code accepts any of the following as equivalent: cmd -ao arg path path cmd -a -o arg path path cmd -o arg -a path path cmd -a -o arg -- path path cmd -a -oarg path path cmd -aoarg path path Example 2: Check Options and Arguments. The following example parses a set of command line options and prints messages to standard output for each option and argument that it encounters. #include <unistd.h> #include <stdio.h> ... int c; char *filename; extern char *optarg; extern int optind, optopt, opterr; ... while ((c = getopt(argc, argv, ":abf:")) != -1) { switch(c) { case 'a': printf("a is set "); break; case 'b': printf("b is set "); break; case 'f': filename = optarg; printf("filename is %s ", filename); break; case ':': printf("-%c without filename ", optopt); break; case '?': printf("unknown arg %c ", optopt); break; } } This example can be expanded to be CLIP-compliant by substituting the following string for the optstring argument: :a(ascii)b(binary)f:(in-file)o:(out-file)V(version)?(help) and by replacing the '?' case processing with: case 'V': fprintf(stdout, "cmd 1.1 "); exit(0); case '?': if (optopt == '?') { print_help(); exit(0); } if (optopt == '-') fprintf(stderr, "unrecognized option: %s ", argv[optind-1]); else fprintf(stderr, "unrecognized option: -%c ", optopt); errflg++; break; and by replacing the ':' case processing with: case ':': /* -f or -o without operand */ if (optopt == '-') fprintf(stderr, "Option %s requires an operand ", argv[optind-1]); else fprintf(stderr, "Option -%c requires an operand ", optopt); errflg++; break; While not encouraged by the CLIP specification, multiple long-option aliases can also be assigned as shown in the following example: :a(ascii)b(binary):(in-file)(input)o:(outfile)(output)V(version)?(help) ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment variables that affect the execution of getopt(): LANG, LC_ALL, and LC_MES- SAGES. LC_CTYPE Determine the locale for the interpretation of sequences of bytes as characters in optstring. USAGE
The getopt() function does not fully check for mandatory arguments because there is no unambiguous algorithm to do so. Given an option string a:b and the input -a -b, getopt() assumes that -b is the mandatory argument to the -a option and not that -a is missing a mandatory argument. Indeed, the only time a missing option-argument can be reliably detected is when the option is the final option on the command line and is not followed by any command arguments. It is a violation of the Basic Utility Command syntax standard (see intro(1)) for options with arguments to be grouped with other options, as in cmd -abo filename , where a and b are options, o is an option that requires an argument, and filename is the argument to o. Although this syntax is permitted in the current implementation, it should not be used because it may not be supported in future releases. The cor- rect syntax to use is: cmd- ab -o filename ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Interface Stability |See below. | +-----------------------------+-----------------------------+ |MT-Level |Unsafe | +-----------------------------+-----------------------------+ The Basic Utility Command syntax is Standard. The CLIP extensions are Evolving. SEE ALSO
intro(1), getopt(1), getopts(1), getsubopt(3C), gettext(3C), setlocale(3C), attributes(5), environ(5), standards(5) SunOS 5.10 13 May 2004 getopt(3C)
All times are GMT -4. The time now is 11:47 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy