Reputation: 3471
Yesterday I was too tired to post correct and specific question. So there it is:
if (t==2){
printf ("abc\n");
printf ("abc = "); scanf ("%f",&r);
printf ("abc = "); scanf ("%d",&n);
printf ("abc = "); scanf ("%d",&k);
a=2*r;
b=2*r;
c=2*r;
for (i=0;i<=n;i++){
float x=(float)rand()/((float)RAND_MAX/a);
float y=(float)rand()/((float)RAND_MAX/b);
float z=(float)rand()/((float)RAND_MAX/c);
if ((x-(r))*(x-(r))+(y-(r))*(y-(r))+(z-(r))*(z-(r))<=(r*r))
m++;
if ( i % k ==0 && i > 0 ){
freopen ( "data.txt","w", stdout );
printf("%s %s %s \n","#","n","Vka");
Vka = ( 2*r*2*r*2*r )*m/i;
printf("% 6.2f % 6.2f \n",n,Vka);
fclose (stdout);
}
}
Vk=(2*r*2*r*2*r)*m/n;
printf ("abc =%d\n", m);
printf ("abc=%d\n", n);
printf("abc =%f", Vk);
}
Unfortunately program does not work as I want it to work. It should export the data to the file "data.txt", but the file still looks like this:
# n Vka
0.00 0.00
Morover the program finishes operation just after creating this file, while I want it to finish its operation on printing Vk in the terminal.
Upvotes: 0
Views: 460
Reputation: 14928
fprintf
There's no reason in this program to mess with stdout
at all.
Upvotes: 1
Reputation: 6684
Use open() syscall to open the file write.txt
and assign it to a fd, say fdout
. Then use dup2(fdout, 1)
for stdout.
You have 3 open pre-def file descriptors by default, in your OS, before you even reach main
:
0 assigned to stdin,
1 to stdout,
2 to stderr.
From the manpage of dup2
:
dup2(int oldfd, int newfd)
makes newfd
to be the copy of oldfd
, closing newfd
first if necessary.
The dup2
call replaces stdout
with your open file write.txt
. So when you printf
the data to stdout
, it will be written to your files rather than to the pre-defined fd's setup by the OS.
This will not only get your job done, the opening and closing of stdout is not your headache anymore.
Upvotes: 0