c++ - 当文件指针在别处声明时,fprintf 不打印到文件

标签 c++ file printing

我有以下文件- SymbolTable.cppSymbolTable.hdemo.ydemo.llog.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/

相关文章:

c++ - 引用为类成员初始化

c++ - 为什么 std::future 从 std::packaged_task 和 std::async 返回的不同?

unix - 目录路径变量是否应该以斜杠结尾?

html - 在所有页面上打印页眉/页脚(打印模式)

c++ - 包含 qgis 头文件时出错

c++ - 这可以做到吗?

file - 如何在 osx 上实现 linux 的 inotify-tools shell 方法

file - 是否有 BoxedApp SDK 的替代品?

python - 如何在控制台的单行上显示倒计时?

c - 试图让这个显示功能起作用