Operating System - HP-UX
1754809 Members
3691 Online
108825 Solutions
New Discussion юеВ

A simple C langauage w/ the basic input/output

 
SOLVED
Go to solution
Insu Kim
Honored Contributor

A simple C langauage w/ the basic input/output

I wrote a very simple C program for any convenience.
I used scanf to get a standard input and printf for standard output like this.

--- a.out ----
main()
{
int instance ;
printf("Input A = ") ;
scanf("%d", &instance) ;
printf(%d, instance) ;
}
-- end of a.out ----

I'd like to save the output to a file.
If I run "a.out" using redirection, the result goes to certain file named but I can't see a message "Input A=" at the shell prompt.

For instance,
# a.out > aaa
"Input A=" is not displayed.
So I have to know what question is in advance.

If I execute "a.out" without any parameters, I can enter a value for the question displayed at the shell prompt but I can't save the result to a file.

Any ideas would be helpful.
Never say "no" first.
2 REPLIES 2
Volker Borowski
Honored Contributor

Re: A simple C langauage w/ the basic input/output

Hi,

if you redirect stdout, you need to prompt on stderr:

fprintf(stderr, "Input A = ") ;
scanf("%d", &instance) ;
printf("Value= %d \n", instance) ;


--- Result :

# a.out
Input A = 23
Value= 23
# a.out > weg
Input A = 23
# cat weg
Value= 23
#

Hope this helps
Volker
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: A simple C langauage w/ the basic input/output

Hi,

You have 3 choices:

1) print your prompt to stderr via fprintf(stderr,
That is not considered good form because stderr should only be used for error messages (but you can use it)

2) If you know that you will always be run as interactive, you can prompt to "/dev/tty".

int main(int argc, char *argv[])
{
int cc = 0;
FILE *f = NULL;

f = fopen("/dev/tty","w+");
if (f != NULL)
{
int instance = 0;
(void) fprintf(f,"Input A: ");
(void) fflush(f);
(void) fclose(f)

scanf("%d", &instance) ;
printf(%d, instance) ;
}
else cc = 2;
return(cc);
}

3) You could pass a filename as an argument
int main(int argc, char *argv)
{
int cc = 0;
if (argc > 1)
{
FILE *f = NULL;
f = fopen(argv[1],"w");
if (f != NULL)
{
int instance ;
printf("Input A = ") ;
scanf("%d", &instance) ;
fprintf(f,"%d", instance) ;
fclose(f);
}
else cc = 2;
}
else cc = 1;
return(cc);
}

Clay
If it ain't broke, I can fix that.