Project

General

Profile

Statistics
| Branch: | Revision:

root / src / scave / filewriter.cc @ a3be1d55

History | View | Annotate | Download (2.32 KB)

1
//=========================================================================
2
//  FILEWRITER.CC - part of
3
//                  OMNeT++/OMNEST
4
//           Discrete System Simulation in C++
5
//
6
//  Author: Andras Varga
7
//
8
//=========================================================================
9

    
10
/*--------------------------------------------------------------*
11
  Copyright (C) 1992-2008 Andras Varga
12
  Copyright (C) 2006-2008 OpenSim Ltd.
13

14
  This file is distributed WITHOUT ANY WARRANTY. See the file
15
  `license' for details on this and other legal matters.
16
*--------------------------------------------------------------*/
17

    
18
#include <stdio.h>
19
#include <locale.h>
20
#include "channel.h"
21
#include "filewriter.h"
22

    
23
#ifdef CHECK
24
#undef CHECK
25
#endif
26

    
27
USING_NAMESPACE
28
#define CHECK(fprintf)    if (fprintf<0) throw opp_runtime_error("Cannot write output vector file `%s'", fileName.c_str())
29

    
30

    
31
FileWriterNode::FileWriterNode(const char *filename, const char *banner)
32
{
33
    f = NULL;
34
    this->fileName = filename;
35
    this->banner = (banner ? banner : "");
36
    this->prec = DEFAULT_PRECISION;
37
}
38

    
39
FileWriterNode::~FileWriterNode()
40
{
41
}
42

    
43
bool FileWriterNode::isReady() const
44
{
45
    return in()->length()>0;
46
}
47

    
48
void FileWriterNode::process()
49
{
50
    // open file if needed
51
    if (!f)
52
    {
53
        f = fopen(fileName.c_str(), "w");
54
        if (!f)
55
            throw opp_runtime_error("cannot open `%s' for write", fileName.c_str());
56

    
57
        setlocale(LC_NUMERIC, "C");
58

    
59
        // print file header
60
        CHECK(fprintf(f,"%s\n\n", banner.c_str()));
61
    }
62

    
63
    int n = in()->length();
64
    for (int i=0; i<n; i++)
65
    {
66
        Datum a;
67
        in()->read(&a,1);
68
        CHECK(fprintf(f,"%.*g\t%.*g\n", prec, a.x, prec, a.y));
69
    }
70

    
71
    if (in()->isClosing())
72
        fclose(f);
73
}
74

    
75
bool FileWriterNode::isFinished() const
76
{
77
    return in()->eof();
78
}
79

    
80
//--------
81

    
82
const char *FileWriterNodeType::getDescription() const
83
{
84
    return "Writes the output into a two-column text file.";
85
}
86

    
87
void FileWriterNodeType::getAttributes(StringMap& attrs) const
88
{
89
    attrs["filename"] = "name of the output file";
90
}
91

    
92
Node *FileWriterNodeType::create(DataflowManager *mgr, StringMap& attrs) const
93
{
94
    checkAttrNames(attrs);
95

    
96
    const char *fileName = attrs["filename"].c_str();
97

    
98
    Node *node = new FileWriterNode(fileName);
99
    node->setNodeType(this);
100
    mgr->addNode(node);
101
    return node;
102
}
103