使用C ++中的fstream写入输出文件

时间:2013-04-18 02:13:47

标签: c++ fstream

假设您有正确的标头并且正在使用命名空间std;在使用fstream将字符串输出到某个输出文件方面,这有点正确吗?我只包含了我的代码的相关文件API部分,因为它的全部内容太长了。我已经包含了iostream和fstream标题。但是我似乎得到了一些特殊的错误,我使用myfile类或对象的方式。

#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;
}

然后将其打印到文件我可以这样做吗?

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

Sim_Sin()和Sim_Cos()返回double值,buf只是一个格式化的字符串。我试图在互联网上应用一些资源,但它似乎不同意我的实现(这显然是错误的)。

以下是错误

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>]

1 个答案:

答案 0 :(得分:0)

这几乎肯定正确。

目前,我将忽略其他问题,解决写作问题。写作本身最明显的问题是你几乎总是希望某事将一个值与下一个值分开。它可以是空格,逗号,制表符,换行符......,但你几乎需要一些东西。没有它,基本上不可能弄清楚哪个数字属于哪个数字 - 例如:1234.56789.876

因此,在写出数据时,您希望在信息之间加入可识别的内容:

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

其次,endl 几乎永远不可取。许多(大多数?)认为它只是在输出中添加了一个新行,但它也刷新流。只要您只编写一行或两行数据,这可能无关紧要,但如果您编写的数据太多,则会严重降低代码速度。

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

在相对罕见的情况下,你真的想要刷新流,我建议使用std::flush来明确这个意图。

编辑:编辑后,您似乎也尝试将iostream与C风格FILE *混合(例如,尝试打开流,但提供C风格{{1}作为参数)。我一般建议选择C风格的FILE *(如果你别无选择)或iostreams(如果可能的话)并坚持使用。像你正在做的那样混合两者不仅会导致很多混乱,而且在某些情况下也会减慢你的代码速度(保持两者协调的额外时间)。

FILE *