我有以下文件- SymbolTable.cpp
、SymbolTable.h
、demo.y
、demo.l
和 log.txt
驱动函数(main)在demo.y
文件中。
我在 demo.y
中声明了 FILE *logout
。但是当我执行 fprintf(logout,"print sth");
时SymbolTable.cpp
的功能它不打印任何东西。我已经在剩下的三个文件中添加了头文件,并且还在其他文件中包含了extern FILE *logout
。
为了使 fprintf
正常工作,还有什么我必须包含的吗?
P.S 当我从 demo.l
fprintf
时打印正常
符号表.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
演示.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;
}
最佳答案
让我们看一下您的 main
函数的一部分:
table = new SymbolTable();
// Other irrelevant code...
logout = fopen("log.txt","w");
当您执行 new SymbolTable()
时,您会创建对象并构造它。这意味着您的 SymbolTable
构造函数将被调用。它发生在您打开文件之前。
这意味着您将调用 fprintf
为文件传递一个空指针,否则未初始化的全局变量将被“零”初始化(这对于指针意味着它们将为空指针)。使用空指针会导致 undefined behavior我会说你不走运程序没有崩溃。
您需要更改顺序,或者在构造函数中不打印任何内容。
关于c++ - 当文件指针在别处声明时,fprintf 不打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935336/