fstream include in the header, but doesn't work?

Viewed 48

I edit the code to clarify the actual code :

#include <fstream>
#include <iostream>

#include <ros/ros.h>
#include <rosbag/bag.h>
#include <std_msgs/Int32.h>
#include <std_msgs/String.h>
#include <nav_msgs/Odometry.h>

std::ofstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);

  

 void callhandler(const nav_msgs::Odometry::ConstPtr& msg)
{
   runtimeFile.open();
if (!runtimeFile)
        {
            std::cout << "cmg_operations_runtime.txt could not be opened.";
        }
         runtimeFile << "tempVector[j]" << ";\t";
         runtimeFile.close ();

        std::cout << "Runtime data stored." << std::endl;
 
}


int main(int argc, char **argv)
{
    ros::init(argc, argv, "main");
    ros::NodeHandle nh;
    ros::Subscriber Listener = nh.subscribe<nav_msgs::Odometry>("/odom", 100, callhandler);
  
    ros::spin();

    return 0;
}

error: `‘runtimeFile’ does not name a type 9 | runtimeFile.open ("cmg_operations_runtime.txt")

The error is the same, I hope someone to help me in this issue?`

1 Answers

In C++ all code must be inside a function. Additionally all C++ programs must have a function called main.

Further your code opens the file twice, once when you declare the runtimeFile variable and once when you call open. Did you not think it strange that you have the file name twice in your code? Don't open files twice. Finally, although it's not an error, there is no need to close the file, that will happen automatically.

Put all that together and you have a legal C++ program.

#include <fstream> 

int main()
{
    std::fstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);
    runtimeFile << "tempVector[j]" << ";\t";
}

EDIT

Some real code has been posted. Based on that I would remove the global runtimeFile variable and make it local to callHandler like the following

void callhandler(const nav_msgs::Odometry::ConstPtr& msg)
{
    std::ofstream runtimeFile("cmg_operations_runtime.txt" , std::ios::out);
    if (!runtimeFile)
    {
        std::cout << "cmg_operations_runtime.txt could not be opened.";
    }
    runtimeFile << "tempVector[j]" << ";\t";
    std::cout << "Runtime data stored." << std::endl;
}

However I can't really see how the latest posted code causes the error described.

Related