当在其他地方声明文件指针时,fprintf不打印到文件

时间:2018-06-19 19:03:19

标签: c++ file printing

我有以下文件-SymbolTable.cppSymbolTable.hdemo.ydemo.llog.txt

驱动程序功能(主)位于demo.y文件中。

我在FILE *logout中声明了demo.y。但是当我在fprintf(logout,"prinit sth");的任何函数中执行SymbolTable.cpp时,它没有打印任何内容。我在其余三个文件中添加了头文件,在其他文件中还包含了extern FILE *logout

为了使fprintf正常工作,我还有什么需要补充的。

当我从fprintf呼叫demo.l时,P.S可以正常打印

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;

}

1 个答案:

答案 0 :(得分:1)

让我们看看您的main函数的一部分:

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

执行new SymbolTable()后,您将创建对象并 construct 。这意味着您的SymbolTable构造函数将被调用。发生在之前打开文件。

这意味着您将通过文件的空指针来调用fprintf,否则未初始化的全局变量将被初始化为“零”(对于指针来说,它们将是空指针) )。使用空指针会导致undefined behavior,我想说您倒霉程序没有崩溃。

您需要更改顺序,或在构造函数中不打印任何内容。

相关问题