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

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

本文关键字:文件 方声明 其他 声明 打印 指针 fprintf      更新时间:2023-10-16

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

驱动程序函数(main(位于demo.y文件中。

我在demo.y年宣布FILE *logout.但是当我fprintf(logout,"prinit sth");任何SymbolTable.cpp功能时,它不会打印任何东西。我已经在其余三个文件中添加了头文件,并在其他文件中包含了extern FILE *logout

我还必须包含其他内容才能fprintf正常工作。

附言当我从demo.l打电话给fprintf时,它打印得很好

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 constructorn");
}

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,"%sn",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传递文件的空指针,否则未初始化的全局变量将"零"初始化(对于指针意味着它们将是空指针(。使用空指针会导致未定义的行为,我会说你很不幸,程序没有崩溃。

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