I have the following C function with a variable number of arguments, which is supposed to search the char* word through a hashtable and write true or false in a file which, if specified, is the second parameter; otherwise, it is stdout.
It works fine if I specify the name of the file, the problem is when I don't (e.g. find("foo")). In this case it writes the result in a file named foo instead of stdout.
What is the cause?
void find(char* word, ...)
{
va_list list;
char *fname = NULL;
va_start(list, word);
FILE* f;
fname = strdup(va_arg(list, char*));
va_end(list);
if (<condition>) // condition suited for the case in which the file name is received
f = fopen(fname, "a");
else
f = stdout;
if (member(word))
fprintf(f, "True\n");
else
fprintf(f, "False\n");
}
In place of <condition> I've tried fname != NULL and strlen(fname) > 0 but those don't apply and it keeps seeing fname as word when fname is not specified.
Thank you very much for any help you can provide.
void find(char* word, char* filename)and checking iffilenameisNULLand if so write to stdout. Also don't forget to close the file, you opened, if you did open a file.