fstream include in the header, but doesn't work? [duplicate] - c++

This question already has an answer here:
c++ - Doesn't name a type
(1 answer)
Closed 6 months ago.
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?`

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

‘gettimeofday’ cannot be used as a function

What am I missing here, this is my main program, I also have a makefile and everything works the error is somewhere in here.
#include <iostream>
#include <observer.h>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
std::fstream in;
int gettimeofday;
//CPUtypeandmodel
struct timeval now;
gettimeofday(&now, NULL);
cout << "Status report as of : " << ctime((time_t*)&now.tv_sec) << endl;
// Print machine name
in.open("/proc/sys/kernel/hostname");
string s;
in >> s;
cout << "Machine name: " << s << endl;
in.close();
return 1;
} //end main
When I try and make the file this happens
observer.cpp: In function ‘int main(int, char**)’:
observer.cpp:13:26: error: ‘gettimeofday’ cannot be used as a function
gettimeofday(&now, NULL);
^
<builtin>: recipe for target 'observer.o' failed
make: *** [observer.o] Error 1
You named a local int variable gettimeofday, which prevents you from calling the function gettimeofday() three lines later. Don't do that. Name the variable something else, or (given it seems unused) just get rid of it.
Your int gettimeofday; is shadowing the function with the same name. You don't even need that variable so remove it.
You need to include ctime and sys/time.h for the functions and classes you use.
You open the file /proc/sys/kernel/hostname for writing, which will fail unless you run the program as root.
The casting to time_t* is not necessary since &now.tv_sec is already a time_t*.
#include <sys/time.h>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
int main() {
// CPUtypeandmodel
timeval now;
if(gettimeofday(&now, nullptr) == 0) // check for success
std::cout << "Status report as of : " << std::ctime(&now.tv_sec) << '\n';
// Print machine name
if(std::ifstream in("/proc/sys/kernel/hostname"); in) { // open for reading
std::string s;
if(in >> s) // check for success
std::cout << "Machine name: " << s << '\n';
} // no need to call in.close(), it'll close automatically here
return 1; // This usually signals failure. Return 0 instead.
} // end main

How to check if a file exists in C++? [duplicate]

This question already has answers here:
Fastest way to check if a file exists using standard C++/C++11,14,17/C?
(23 answers)
Closed 3 years ago.
I want to determine if a file exists in C++ 11
I have the following codes:
ifstream inputFile(c);
if (!inputFile.good()) {
std::cout << "No file found" << '\n';
}
And
if (inputFile.peek() == std::ifstream::traits_type::eof()){
....
}
Which one is correct and idiomatic?
In C++17 you have <filesystem> in which you can do:
namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else std::cout << "nope";
If you're trying to determine if a file exist using C++11 you may want to try this idea
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]){
std::ifstream file("myfile.txt");
if(!file.is_open()){
std::cout << "File not found" << std::endl;
return -1;
}
return 0;
}

fstream does not work well with Pin

I've written a very simple Pin tool that only contains one instrumention function, that is, instruction below. It has no analysis function/callback. Its purpose is to only store the address of instructions that may be executed.
#include <cstdint>
#include <iostream>
#include <fstream>
#include <list>
#include "pin.H"
std::ofstream of1;
std::list<uint64_t> instrList;
uint64_t instrCount = 0;
VOID instruction(INS ins, VOID* v)
{
ADDRINT ip = INS_Address(ins);
of1 << ip << std::endl;
of1.flush();
instrList.push_back(ip);
++instrCount;
}
VOID finishFunc(INT32 code, VOID *v)
{
of1.close();
std::ofstream of2;
of2.open("out2.txt", std::ofstream::out);
of2 << std::hex;
for (std::list<uint64_t>::iterator i = instrList.begin(); i != instrList.end(); ++i)
of2 << *i << std::endl;
of2.close();
std::cerr << "Instruction count: " << instrCount << std::endl;
}
int main(int argc, char* argv[])
{
PIN_Init(argc, argv);
of1.open("out1.txt", std::ofstream::out);
of1 << std::hex;
INS_AddInstrumentFunction(instruction, 0);
PIN_AddFiniFunction(finishFunc, 0);
PIN_StartProgram();
return 0;
}
The contents of the files out1.txt and out2.txt should be the same.
I attached this Pin tool to some programs such as /bin/ls. For them, out1.txt and out2.txt are the same. But when I attach it to gcc compiling a code, out1.txt would have more lines than out2.txt. out2.txt has a number of lines that is equal to instrCount, which seems reasonable. It seems that there's a problem with the fstream corresponding to out1.txt. out1.txt has a number of duplicate lines as compared to out2.txt.
These snippets show where they start to differ (marked with <):
out1.txt:
7f87ceb050a2
7f87ceb050a4
7f87ceb050a5
7f87ceb050a8
7f87ceb050aa
7f87ceb050b2
7f87ceb050b7
7f87ceb050b9
<7f87ceb050a4
<7f87ceb050a5
<7f87ceb050a8
<7f87ceb050aa
<7f87ceb050b2
<7f87ceb050b7
<7f87ceb050b9
<7f87ceb050b2
45218c
<7f87ceb050b7
45218e
<7f87ceb050b9
452190
out2.txt:
7f87ceb050a2
7f87ceb050a4
7f87ceb050a5
7f87ceb050a8
7f87ceb050aa
7f87ceb050b2
7f87ceb050b7
7f87ceb050b9
45218c
45218e
452190
I used a PIN_LOCK inside instruction function, but that doesn't change anything. I also tried to write into output files using fprintf, but the problem still exists.
Any idea how to solve this issue?

Standard functions and operations not working in class constructor

I am trying to make my first class with a constructor and it seems to be acting strangely.
My class is derived from filebuf and for some reason, I am unable to open it in the constructor.
I tried to add a cout statement for debugging, but the << operator is not recognized.
#include <iostream>
#include "bin.h"
int main()
{
bin myBin("e:\Temp\test.txt");
system("PAUSE");
return 0;
}
bin.h
#pragma once
#include <fstream>
#include <cstdlib>
#include <cstring>
class bin : private std::filebuf {
int buffSize = 1000;
char* buffer;
unsigned int length;
short int buffCounter;
public:
bin(std::string fileName)
{
open(fileName.c_str(), std::ios::in | std::ios::out | std::ios::trunc);
if (!is_open())
std::cout << "ERROR: failed to open file " << fileName << std::endl;
//set all IO operations to be unbufferred, buffering will be managed manually
setbuf(0, 0);
//create buffer
buffer = new char[buffSize];
};
virtual ~bin()
{
delete buffer;
};
};
bin myBin("e:\Temp\test.txt");
You have to correct above line as follows:
bin myBin("e:\\Temp\\test.txt");
DEMO: http://cpp.sh/7b4k
It looks like you need:
#include <iostream>
To use std::string you need:
#include <string>
The iostream include may have forward-declared std::string but without the full definition you don't get operator<< (or c_str()).
Some other answerers may be unable to reproduce your problem because different standard libraries might have their iostream fully do #include <string> (this is permitted but not required).
std::cout << "ERROR: failed to open file " << fileName << std::endl;
Should be
std::cout << "ERROR: failed to open file " << fileName.c_str() << std::endl;
std::cout doesn't always accept std::string but does accept const char *

Why doesn't my function produce output

I'm doing a C++ assingment for a class and I haven't used C++ in a decade so this might be something I'm missing that is simple; however ,I can't seem to figure it out.
I have a class I defined with a function that is producing no output; it looks like it's not even running and I don't have a clue why. Could someone point out my problem to me?
Issue: cout from the function getwords of the class readwords doesn't display any results.
Here is my class:
class readwords {
private:
char c;
//string aword;
public:
void getwords(std::istream& file) {
cout << "I got here" << std::flush;
/*while(file.good()) {
cout << "I got here\n";
c = file.get();
if(isspace(c)) cout << "\n"; //continue;
if(isalnum(c)) {
cout << c; //aword.insert(aword.end(),c);
}
}
*/
}
};
Which is being called from my main:
#include <fstream>
#include <stdlib.h>
#include "lab1.h"
using namespace std;
readwords wordsinfile;
words wordslist;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) {
// Looks like we have no arguments and need do something about it
// Lets tell the user
cout << "Usage: " << argv[0] <<" <filename>\n";
} else {
// Yeah we have arguements so lets make sure the file exists and it is readable
ifstream ourfile(argv[1]);
if (!ourfile.is_open()) {
// Then we have a problem opening the file
// Lets tell the user and exit
cout << "Error: " << argv[0] << " could not open the file. Exiting\n";
exit (1);
}
// Do we have a ASCII file?
if (isasciifile(ourfile)) {
cout << "Error: " << argv[0] << " only can handle ASCII or non empty files. Exiting\n";
exit(1);
}
// Let ensure we are at the start of the file
ourfile.seekg (0, ios::beg);
// Now lets close it up
ourfile.close();
}
// Ok looks like we have past our tests
// Time to go to work on the file
ifstream ourfile2(argv[1]);
wordsinfile.getwords(ourfile2);
}
Thank you for any help you can provide.
Try to use a debugger. Most IDEs (NetBeans, Code::Blocks, etc) provide an interactive interface with gdb.
I just compiled and ran your code, but nothing wrong with the code itself,
except that I needed to include to use the 'cout' method.
"I got here" has been successfully displayed in my ubuntu machine.
What is your execution environment? You should check it first.
The problem appears to be redefining my own class. When actually coding the function I needed to use:
in readwords::countwords(std::istream& file) {
....
}
Once doing this output produced fine.