freopen....

This is a discussion on freopen.... within the C Programming forums, part of the General Programming Boards category; I had a program which accepted input file on the command line and redirected output to file specified in the ...

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305

    freopen....

    I had a program which accepted input file on the command line and redirected output to file specified in the command line. So it was essentially

    Code:
    $ ./name_of_program <input_file >output_file
    Code:
    void  main(int Argc, char *Argv[])
    /*    ----  */
    {
        // Initialise the variables
    
        /*  Process options  */
    
        while ( (o = getopt(Argc, Argv, "nNus:a:f:g:V:d:A:w:l:t:m:v:")) != EOF )
        {
    	if ( FirstTime )
    	{
    	    printf("\n    Options:\n");
    	    FirstTime = false;
    	}
    
    	switch (o)
    	{
    	    case 'n': // Do some calculations
                           break;
    
    	    case 'N': //Do some calculations
    			break;
             }
           }
    Now I made some modifications to this program to get it working with Java Native Interface. Also I used freopen to redirect stdin and stdout to the files. One other change that I made was that my program made use of getopt() function to parse the command line arguments. Since now I am not running it on the command line I put the calculations that were being done before the getopt() part. So my modified code looks like this.

    Code:
    void enter() {
    
        freopen("inputfile","r", stdin);
        freopen("outputfile","w", stdout);
        enter();
        fclose(stdin);
        fclose(stdout);
        
        // Run again with a different input and output file
        freopen("inputfile","r", stdin);
        freopen("outputfile","w", stdout);
        enter();
        fclose(stdin);
        fclose(stdout);
    
    }
    
    void  main()
    /*    ----  */
    {
        // Initialise the variables
    
       // Do some calculations
       // Do some calculations
        /*  Process options  */
    
        while ( (o = getopt(Argc, Argv, "nNus:a:f:g:V:d:A:w:l:t:m:v:")) != EOF )
        {
    	if ( FirstTime )
    	{
    	    printf("\n    Options:\n");
    	    FirstTime = false;
    	}
    
    	switch (o)
    	{
    	    case 'n': // Do some calculations
                           break;
    
    	    case 'N': //Do some calculations
    			break;
             }
           }
    I got my executable and ran the program with just one input and output file and it ran smoothly. But when I ran it with two input and output files it crashes giving me a Segmentation Fault. If i put printf after I dont see the output being redirected to my output file.

    Code:
        // Run again with a different input and output file
        freopen("inputfile","r", stdin);
        freopen("outputfile","w", stdout);
        printf("\nI am here");
    Any clues on if there is an issue with using freopen multiple times.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    A few things:

    1. int main, not void main

    2. for printf's, especially ones for debugging, put the \n at the end. For extra bonus points, follow it with fflush(stdout)

    3. Better yet, print to stderr, since you're mucking about with stdout to begin with.

    4. If you really want to know where it is crashing, use the debugger and then use 'bt' to show you where you really are.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Code:
    void enter() {
    
        freopen("inputfile","r", stdin);
        freopen("outputfile","w", stdout);
        enter();
        fclose(stdin);
        fclose(stdout);
        
        // Run again with a different input and output file
        freopen("inputfile","r", stdin);
        freopen("outputfile","w", stdout);
        enter();
        fclose(stdin);
        fclose(stdout);
    
    }
    This looks like a recipe for disaster... a recursive function that will never exit and simply keep calling itself over and over again.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    The freopen() function opens the file whose name is the string pointed
    to by path and associates the stream pointed to by stream with it. The
    original stream (if it exists) is closed. The mode argument is used
    just as in the fopen() function. The primary use of the freopen()
    function is to change the file associated with a standard text stream
    (stderr, stdin, or stdout).
    ....
    Last edited by Bayint Naung; 08-23-2010 at 08:11 AM.

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    Running out of stack space with infinite recursion probably results in a segfault.

    It's also probably not a good idea to do 'bt' in a debugger in that case
    It might take a while to print out all the recursive frames
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Oops actually I made a mistake while posting the code segment. Here is the code segment that I am using.

    Code:
    int main(){
    	
    	freopen("member.d", "r", stdin);
    	freopen("log.txt", "w", stdout);
    	enter();
    	fclose(stdin);
    	fclose(stdout);
    	return 0;
    }
    
    void  enter()
    /*    ----  */
    {
        int		o, i, Cases, Errors;
        extern char	*optarg;
        extern int	optind;
        Boolean	FirstTime=true;
        Var		V;
        extern Var	*Arg;	/* in literal.c */
        Relation	R;
        Tuple	Case;
        char	Line[200], PlusOrMinus;
    
        /* Check overlaying of Const and float */
    
        if ( sizeof(Const) != sizeof(float) )
        {
    	printf("Integers and floating point numbers are different sizes\n");
    	printf("Alter declaration of type Const (defns.i) and recompile\n");
    	exit(1);
        }
    
        printf("FOIL 6.4   [January 1996]\n--------\n");
    	if ( FirstTime )
    	{
    	    printf("\n    Options:\n");
    	    FirstTime = false;
    	}
    
    	MINACCURACY = 0;
    	printf("\tminimum clause accuracy %g%%\n",MINACCURACY);
    	MINACCURACY /= 100;
    Also I was able to trace to the location where Segmentation fault occurred. But the issue which keeps me wondering is the fact why does it not crash on first invocation at that point. Should I post the gdb output as well?
    Last edited by roaan; 08-23-2010 at 08:28 AM. Reason: Added in the "int main".

  7. #7
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Quote Originally Posted by Bayint Naung View Post
    The original stream (if it exists) is closed.
    Okay If I understand then I should be doing probably this.

    Code:
    int main(){
    	
    	freopen("err.txt","w", stderr);
    	FILE* input = freopen("member.d", "r", stdin);
    	FILE* output = freopen("log.txt", "w", stdout);
    	enter();
    	fflush(input);
    	fflush(output);
    	fclose(input);
    	fclose(output);
    	
    	FILE* in = freopen("member.d", "r", input);
    	FILE* out = freopen("log1.txt", "w", output);
    	printf("\nI am here");
    	enter();
    	fflush(in);
    	fflush(out);
    	fclose(in);
    	fclose(out);
    
    	return 0;
    }
    
    void  enter()
    /*    ----  */
    {
        int		o, i, Cases, Errors;
        extern char	*optarg;
        extern int	optind;
        Boolean	FirstTime=true;
        Var		V;
        extern Var	*Arg;	/* in literal.c */
        Relation	R;
        Tuple	Case;
        char	Line[200], PlusOrMinus;
    
        /* Check overlaying of Const and float */
    The good thing is that now I don't get "Segmentation Fault". But my second call to enter() is not generating the output that is genenrated in the first call.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    > But the issue which keeps me wondering is the fact why does it not crash on first invocation at that point.
    Who knows, you keep posting incomplete code.

    There's nothing special about the first iteration, or the second, or the 435365th
    If you screw up, then when (or even if) it ever gets around to crashing is entirely random.

    LOOK at the variables around where it crashes (use the debugger!) and start theorising as to how it got to that broken state. Then fix your code based on that theory and try again.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Redirecting stdout, stderr and stdin
    By iwabee in forum Linux Programming
    Replies: 9
    Last Post: 05-16-2005, 05:42 PM
  2. exec and buffered output
    By optimus in forum C Programming
    Replies: 5
    Last Post: 04-26-2004, 03:25 AM
  3. freopen and strings
    By Juicehead in forum C Programming
    Replies: 3
    Last Post: 11-21-2002, 07:35 AM
  4. Replies: 9
    Last Post: 07-01-2002, 07:50 AM
  5. help with redirecting std output & errors
    By fergie in forum Linux Programming
    Replies: 3
    Last Post: 04-22-2002, 02:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21