Reputation: 39
I have a program that either reads an input from a file or from the keyboard. I have found a way to decide whether the input should be inserted from a file or from keyboard.
I need to implement that decision with an easy way, as I don't want to copy my code 2 times for each type of input.
I tried something like the code bellow but worked only for an input file (arv == 1), while it gets a segmentation fault from stdin.
error after debugging for arg == 0
(_IO_fgets (buf=0xbffffaac "\030\031\023", n=100, fp=0x0) at iofgets.c:52)
Code:
FILE *fp;
if (arg = 1)
fp = fopen (operationfile, "r");
else
fp = stdin;
while (fgets(buffer, sizeof(buffer), fp) != NULL)
Is there a fast way to do this?
Upvotes: 0
Views: 2823
Reputation: 17041
if(arg == 1) /* == */
{
....
should take care of much of your trouble. arg = 1
sets arg
to 1 and always succeeds, so the fp=stdin;
branch is never used.
Also, your question doesn't show how arg
is assigned. Is it the first parameter of main()
? If so, that's usually called argc
. If you use the conventional name, other developers will have an easier time understanding your code.
Edits
As @MayurK points out, using 1 == arg
rather than arg == 1
will help the compiler protect you from this.
As @EdHeal points out, some compilers have options to check for if(arg=1)
, since it's rarely what you want. In GCC, -Wint-in-bool-context
and -Wparentheses
are useful (or, better yet, just fire up -Wall
!).
Upvotes: 5