Re: [LIP] Avoid use of global variables
Saju Pillai <[email protected]>
| Newsgroups | gmane.user-groups.linux.india.programmers |
|---|---|
| Message-ID | <[email protected]> |
Kumar Appaiah wrote:
>
> Now, I wish to add a feature by which I can allow several files in a
> directory tree to be processed. I, therefore, use the ftw function
> (nftw variant). However, notice that I now have to call my process
> file function from the "callback" function for nftw:
>
> static int
> ftw_handler(const char *fpath, const struct stat *sb,
> int tflag, struct FTW *ftwbuf)
> {
> /* ... */
>
> processFile(filename, <variables which depend on command line arguments>);
> /* ... */
> return 0;
> }
>
> int
> main(int argc, char *argv[])
> {
> /* Get command line parameters */
> /* ... */
>
> if (nftw((argc < 2) ? "." : argv[1], ftw_handler, 20, flags)
> == -1) {
> perror("nftw");
> exit(1);
> }
> /* ... */
> return 0;
> }
>
> My question is, how do I pass on the elements of the command line
> arguments which alter the behaviour of processFile while calling it?
> It seems to me that the easiest way would be to use global variables,
Yes.
> but is there an elegant way by which this can be avoided? Or, is it
> acceptable to use global variables in this situation?
Usually callbacks accept a void *mystuff style context object to solve
this exact problem. Since nftw() doesn't let you pass in a context
object I don't see how you can avoid using globals.
Also using globals is not a bad thing - particularly in write once, read
many cases.
srp
--
http://saju.net.in
------------------------------------------------------------------------------