fprintf 不打印到文件,当文件指针在其他地方声明时
fprintf not printing to a file,when file pointer declared elsewhere
我有以下文件-SymbolTable.cpp
,SymbolTable.h
,demo.y
,demo.l
和log.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
传递文件的空指针,否则未初始化的全局变量将"零"初始化(对于指针意味着它们将是空指针(。使用空指针会导致未定义的行为,我会说你很不幸,程序没有崩溃。
您需要更改顺序,或者不打印构造函数中的任何内容。
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 调用在 HXX 文件中声明的静态数据成员
- 如何在 c++ 的不同文件中声明类?
- 如何在头文件中声明类模板(由于循环依赖关系)
- 在指向现有内存地址的 hpp 文件中声明成员函数的最佳方法
- 当我可以在头文件中声明和定义所有文件时,为什么要创建一个.cpp文件?
- 如果您只需要在 .h 文件中声明函数.cpp是否需要在 .h 文件中声明函数?
- 全局自动变量可以在 h 文件中声明吗?
- 为什么我的.cpp文件无法解析 .h 文件中声明的变量?
- 在头文件中声明和初始化向量
- 如何在多个文件中声明全局 std::vector 2d 数组?C++
- 我们是否应该在项目中包含的所有文件中声明外部变量
- (编辑)如何在Windows中导出模板专业,并在CPP文件中声明源
- 为什么文件命令声明可执行文件包含"debug_info"
- 是否必须在C++文件中写入头文件中声明的变量的类型
- 在.h文件中声明正态分布生成器
- 如何为头文件中声明的指针设置值
- 当外部变量在其他文件中声明不同时,如何使G 产生警告
- c在.h文件中声明阵列列表
- 使用指向在头文件中声明的函数中的结构的指针