• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 517
  • Last Modified:

using fprintf to write to a file...

Ive inherited some code which I have modified and it works fiine!

Essentially, it reads in a stream from stdin, does stuff and writes it out to a new user defined stream.
Ive used streams just because I thought it would give me most flexibility for future development.

I wrapped my C binary in a shell wrapper and redirected my stream output by using  binary_name 6>file.out

For operational reasons I need to change that so that instead of sending my fprintf to my stream, I send it straight to the file.

That wouldnt seem to be an insummountable problem but I cant seem to do it!!

Can anyone help?  I thought it should be easy for me to change fprintf(STREAM,string) to fprintf(FILE,string) because I thought an open file took a stream as its input anyway, so in essence I should just be able to somehow point my stream to the file?

Julian

0
stummj
Asked:
stummj
  • 3
  • 2
2 Solutions
 
stummjAuthor Commented:
If anyone needs to chat to get clarifications I am on msn right now julian@stumm.me.uk
0
 
jkrCommented:
What about using 'freopen()', e.g. like

/* FREOPEN.C: This program reassigns stderr to the file
 * named FREOPEN.OUT and writes a line to that file.
 */

#include <stdio.h>
#include <stdlib.h>

FILE *stream;

void main( void )
{
   /* Reassign "stderr" to "freopen.out": */
   stream = freopen( "freopen.out", "w", stderr );

   if( stream == NULL )
      fprintf( stdout, "error on freopen\n" );
   else
   {
      fprintf( stream, "This will go to the file 'freopen.out'\n" );
      fprintf( stdout, "successfully reassigned\n" );
      fclose( stream );
   }
   system( "type freopen.out" );
}
0
 
avizitCommented:
show what was the original code and what you changed it to ..

only the modified part should be sufficient I thin ....
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
stummjAuthor Commented:
The original code just wrote to the stdout stream. I just copy and pasted really, and wrote to my custom stream instead.
0
 
avizitCommented:
say you had

fprintf(stdout, "xyz");

you can put the following code in its place

File *fp;

fp = fopen("newfile.txt",  "w" );
if(fp == NULL ) { print error and exit or whatever suits you }

fprintf(fp, "xyz");

fclose(fp);   // when yuo are done close the file
0
 
stummjAuthor Commented:
Thanks both.

I simply had to change:

stream=fdopen(descriptor,type)

to

stream = fopen(filename,type)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now