afsara_ben
afsara_ben

Reputation: 672

fprintf not printing to a file,when file pointer declared elsewhere

I have the following files- SymbolTable.cpp, SymbolTable.h, demo.y,demo.l and log.txt

The driver function(main) is in the demo.y file.

I declared FILE *logout in demo.y.But when i do fprintf(logout,"prinit sth");in any function of SymbolTable.cpp it is not printing anything. I have added the header file in the remaining three files, and also included extern FILE *logout in the other files.

Is there anything else that I have to include so that fprintf works properly.

P.S it prints fine when i call fprintf from demo.l

SymbolTable.cpp

#include "SymbolTable.h"
#include "SymbolInfo.h"
#include "ScopeTable.h"
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<map>
#include<string>
#include<vector>
using namespace std;

int tableSize = 7;
extern FILE *logout;

SymbolTable::SymbolTable()
{
    cout<<"in SymbolTable constructor"<<endl;
    fprintf(logout,"in SymbolTable constructor\n");

}

demo.l

%option noyywrap
%{
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

#include "SymbolTable.h"
#include "SymbolInfo.h"
#include "ScopeTable.h"
#include "y.tab.h"

void yyerror (char *);
extern YYSTYPE tag ;    
extern SymbolTable *table;
extern int tableSize;

extern FILE *logout;
extern FILE *temp;

%}

id [a-z]*
newline \n
ADDOP "+"
digit[0-9]

%%
......remaining code

demo.y

%{
#include<stdio.h>
#include<stdlib.h>  
#include<string.h>
#include "SymbolTable.h"
#include "SymbolInfo.h"
#include "ScopeTable.h"
//#define yydebug 1

int yyparse(void);
int yylex(void);
extern char * yytext;
extern FILE * yyin;
extern int tableSize;
//extern FILE *temp;

SymbolTable *table;

FILE *logout;
void yyerror (const char *s)
{
    fprintf(stderr,"%s\n",s);
    return;
}

%}
%%

%%
int main(int argc, char *argv[])
{

    table = new SymbolTable();
    FILE *fp;
    if((fp = fopen(argv[1],"r")) == NULL)
    {
        printf("cannot open file");
        exit(1);
    }
    logout = fopen("log.txt","w");
    //temp = fopen("temp.txt","w");
    yyin = fp;
    yyparse();
    return 0;

}

Upvotes: 0

Views: 308

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

Lets take a look at part of your main function:

table = new SymbolTable();
// Other irrelevant code...
logout = fopen("log.txt","w");

When you do new SymbolTable() you create the object and construct it. That means your SymbolTable constructor will be called. And it happens before you open the file.

This means that you will call fprintf passing a null pointer for the file, as otherwise uninitialized global variables will be "zero" initialized (which for pointers means they will be null pointers). Using a null pointer leads to undefined behavior and I would say that you're unlucky the program didn't crash.

You need to change the order, or not print anything in the constructor.

Upvotes: 1

Related Questions