Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Assuming you have the proper headers and are using namespace std; is this somewhat correct in terms of using fstream to output a string to some output file? I only included the relevant file API parts of my code as the entirety of it was too long. I've included the iostream and fstream headers. However I seem to get some particular errors, with the way im using the myfile class or object.

#include <curses.h>
#include <math.h>
#include "fmttime.h"
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>                      // Needed for the file API
#include <iostream>                     // File API headers for C++
#include <fstream>
using namespace std;

// Enumeration list for the colors of the grid, title, sin and cos waves
enum colors
{
        Gridcolor = 1,
        Titlecolor,
        Sincolor,
        Coscolor,
};

void Sim_Advance(int degrees);          // Function prototype for Phase angle
double Sim_Cos();                       // Function that calculates cos
double Sim_Sin();                       // Function that calculates Sin
char* usage();                          // Function which returns error mssg
static const double PI = (M_PI/180);    // Degrees to radian factor
static double PA = 0;                   // Phase angle
static double x;                        // X dimension of screen
static double y;                        // Y dimension of screen
static int delay1 = 300000;             // 300ms Delay
static int currenty = 0;                // Y index
static const int buffsize = 25;         // Size of the character buffer for time

// Function prototype for frame of plot function
void frame(const char* title, int gridcolor, int labelcolor);

// Function prototype for the symbols that form the plot
void mark(WINDOW* window, char ch, int color, double value);

int main(
        int argc,                       // Number of command line arguements
        char* argv[]                    // String of each command line
        )

{
    initscr();                          // Curses.h initilizations
    cbreak();
    nodelay(stdscr, TRUE);
    noecho();                           // Supress character inputs on screen
    start_color();                      // Enable Bg/Fg colors

    // Color Initializations for the enumeration list

    init_pair(Gridcolor, COLOR_RED, COLOR_BLACK);
    init_pair(Titlecolor, COLOR_GREEN, COLOR_BLACK);
    init_pair(Sincolor, COLOR_YELLOW, COLOR_BLACK);
    init_pair(Coscolor, COLOR_MAGENTA, COLOR_BLACK);


    int keyhit;                         // Holder for the getch command
    int ctr = 1;                        // Exit flag
    int degrees = 10;                   // Interval to be added to phase
    int enablelog = 0;                  // Flag for Logging enable
    int disabletrunc = 0;               // Flag for logging without truncation
    char* outputName = NULL;            // Name of output program

    FILE* pLog;                         // File pointer for O/P write
    getmaxyx(stdscr,y,x);               // Find max x and y values of stdscrn

    // Defining a new window in the terminal for printing the plot

    WINDOW* Window = newwin(y-4, x, 2, 0);

    x = x - 2 - buffsize;               // Move window to allow for timestamp
    scrollok(Window, TRUE);             // Enable scrolling window

    // Title string for the plotter

    char cTitle[] = {"Real time Sine/ Cosine Plot"};

    //  API Code for FILE output
    ofstream myfile (pLog);             //
    int i = 1;                          // Index for how many times getopt needs
                                        // to be called. Starts at 1 to offset
                                        // program call string, without options
    while (i < argc)
    {
        switch (getopt (argc, argv, "ao:"))
        {
                case 'a':
                disabletrunc = 1;
                break;

                case 'o':
                enablelog = 1;
                outputName = optarg;    // Gets the name of textfile

                // Open the file as designated by the user
                // and assign it to the file pointer pLog
                // The following if else statement opens the file for
                // logging in 2 distinct modes, extended and truncation

                if (disabletrunc == 1)
                {
                    pLog = myfile.open (outputName, ios::out | ios::app);
                }
                else
                {

                // Print with truncation

                    pLog = myfile.open (outputName, ios::out | ios::trunc);
                }

                break;

                // Case of error, print usage message

                case '?':
                endwin();
                puts(usage());
                return 0;

                break;

                // No more options on command line

                case -1:
                i = argc;
                break;
        }
        ++i;
    }

    // If only '-a' is enabled then this is still an error case
    // This if statement handles that case

    if (disabletrunc == 1 && enablelog == 0)
    {
        endwin();
        puts("\nWARNING: -a must be used in conjuction with -o FILENAME");
        puts(usage());
        return 0;
    }


        while (ctr == 1)                // This will run the program till
        {                               // exit is detected (CTRL-X)
            usleep(300000);             // Delays program execution
            keyhit = getch();

            frame(cTitle, Gridcolor, Titlecolor);  // Prints out the frame once
           struct timeval tv;
            char buf[buffsize];                    // Buffer being sent to formattime
            gettimeofday(&tv, NULL);               // calling function for epoch time
            formatTime(&tv, buf, buffsize);        // Calling formaTime for timestamp
            wattrset(Window, COLOR_PAIR(Gridcolor));
            wprintw(Window,"%s", buf);
            wrefresh(Window);

            mark(Window,'|', Gridcolor, 0);
            mark(Window,'C', Coscolor, Sim_Cos());
            mark(Window,'S', Sincolor, Sim_Sin());

            // Scroll to next y coordinate

            wmove(Window, currenty, buffsize + x);
            wrefresh(Window);
            wprintw(Window, "\n");
            wrefresh(Window);

            currenty = getcury(Window);


            // Print desired data into the output file

            if (enablelog == 1)
                myfile << buf << Sim_Sin() << Sim_Cos() << endl;
                //fprintf(pLog, "%s, %f, %f\n", buf, Sim_Sin(), Sim_Cos());

            Sim_Advance(degrees);       // Advances PA by "degrees" value (10)


                if (keyhit == 24)
                {
                    ctr = 0;            // Exit flag set
                }

        }

        // Only close the file if file exists to avoid error
        if (enablelog == 1)
        {
            myfile.close(pLog);
            //close(pLog);
        }

    endwin();
    return 0;
}

// This function will provide an usage message and give the user
// a list of acceptable option characters to use with the program
// when a non valid option character is used or used improperly

char* usage()
{
    // String to be printed as the error message

    static char errors[] = {"\nSorry Invalid Option entered\n\n"
                            "Please Enter a Valid Option specifier:\n"
                            "-o FILENAME      Enable logging to specified "
                            "output file: FILENAME\n"
                            "-a          Enable extended logging"
                            " rather than truncated logging\n\n"
                            "Please Note: -a cannot be used without -o"
                            " FILENAME\n"};

    return errors;
}

and then to print it to the file can i do this?

myfile << buf << Sim_Sin() << Sim_Cos() << endl;
myfile.close(pLog);

Sim_Sin() and Sim_Cos() return double values, and buf is just a formatted string. I tried to apply some of the resources on the internet however it doesn't seem to agree with my implementation (which is obviously wrong).

Here are the errors

plot.cc: In function 'int main(int, char**)':
plot.cc:93: error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(FILE*&)'
/usr/include/c++/4.4/fstream:623: note: candidates are: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.4/fstream:608: note:                 std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.4/iosfwd:84: note:                 std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(const std::basic_ofstream<char, std::char_traits<char> >&)
plot.cc:117: error: expected ';' before 'pLog'
plot.cc:124: error: void value not ignored as it ought to be
plot.cc:208: error: no matching function for call to 'std::basic_ofstream<char, std::char_traits<char> >::close(FILE*&)'
/usr/include/c++/4.4/fstream:736: note: candidates are: void std::basic_ofstream<_CharT, _Traits>::close() [with _CharT = char, _Traits = std::char_traits<char>]
share|improve this question
1) What errors are you getting? 2) Can you post a minimal complete example? – Beta Apr 18 at 2:18
Ahh sorry, I will post the complete code then. I just didnt want someone to read through all of it :S – Ryan Apr 18 at 2:19
I said minimal! When you are trying to use an unfamiliar technique (like file I/O) you should try it in isolation first, not graft it into the middle of a huge function. – Beta Apr 18 at 2:21
I've already done the file API in C, however I need to port it over to C++ now. I assumed it would be an easy task how wrong i was! – Ryan Apr 18 at 2:22
I actually don't think I need the pLog there....just the Outputname arguement.... – Ryan Apr 18 at 2:25
show 4 more comments

1 Answer

up vote 0 down vote accepted

This is almost certainly not correct.

For the moment, I'm going to ignore other issues, and only address the writing itself. The most obvious problem with the writing itself is that you almost always want something to separate one value from the next. It can be a space, a comma, a tab, a new-line, ..., but you pretty much need something. Without that, it'll be essentially impossible to figure out which digits belong to which number -- for example: 1234.56789.876

So, when writing out the data, you want to put something recognizable between the pieces of information:

myfile << buf << "\t" << Sim_Sin() << "\t" <<  Sim_Cos() << endl;

Second, endl is almost never desirable. Many (most?) think of it as only adding a new-line to the output, but it also flushes the stream. As long as you're only writing a line or two of data, that probably doesn't matter, but if you're writing much data, it can slow your code down tremendously.

myfile << buf << "\t" << Sim_Sin() << "\t" <<  Sim_Cos() << "\n";

In the relatively rare case that you really want to flush the stream, I'd advise using std::flush to make that intent clear.

Edit: After your edit, it appears that you're also trying to mix iostreams with C-style FILE *s (for example, attempting to open a stream, but supplying a C-style FILE * as the parameter). I'd generally advise picking either C-style FILE *s (if you have no choice) or iostreams (if possible) and sticking to that one throughout. Mixing the two like you're doing can lead not only to a lot of confusion, but can also slow down your code in some cases (extra time to keep the two coordinated).

std::ofstream myfile("name.txt");
myfile << buf << "\t" << Sim_Sin() << "\t" <<  Sim_Cos() << "\n";
share|improve this answer
I plan to use iostreams, so I realize that i have to rid myself of pLog and just pass the character string file name. – Ryan Apr 18 at 2:37
It works! Thanks! – Ryan Apr 18 at 2:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.