‘gettimeofday’ cannot be used as a function - c++

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

Related

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

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.

Program to read from file line by line

I've been trying to write a code to read from a file line by line:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin("Story.txt");
// ins.open("Story.txt", ios::in);
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
else{
char a[100];
do
{
jin.getline(a, 100);
cout << a << endl;
}
while (!jin.eof());
jin.close();
return 0;
}
}
However, on executing this program on Visual Studio Code on Windows, it behaves as infinite loop.
Can someone tell what's wrong?
(I am sure that the file Story.txt exists, no doubt about that)
When std::istream::getline has read 100-1 characters (without finding a newline,\n), it will set the failbit on the stream. This prevents further reading on the stream (unless you reset that state). It does however not set eofbit so you are now in a bit of a pickle. The failbit prevents further reading, and eof() returns false, because eofbit is not set - it will therefore loop indefinitely.
If at least one of the lines in Story.txt is longer than 99 chars, the above is what will happen.
The easiest way out is to use a std::string and std::getline instead:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
std::string a;
while(std::getline(jin, a)) {
std::cout << a << '\n';
}
return 0;
}
If you really do not want to use std::getline and std::string, you can, but it's much harder:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
char a[100];
while(true) {
jin.getline(a, 100);
std::cout << a; // output what we got
if(jin) {
// got a complete line, add a newline to the output
std::cout << '\n';
} else {
// did not get a newline
if(jin.eof()) break; // oh, the end of the file, break out
// reset the failbit to continue reading the long line
jin.clear();
}
}
}
jin.eof() will only return true if a eof-token is found, and this will not happend unless the file is open. That is what causing your infinite loop.
Then you would probably want something like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin{"Story.txt"};
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
for (std::string a; std::getline(jin, a);) { // Read every line
cout << a << "\n";
}
// jin is closed when going out of scope so no need for close();
return 0;
}

It's possible suppress output about of one function?

In my program I use an external function which generates output to me and I don't want it not to be generated by that function alone,
it's possible?
int main()
{
int a;
//I don't want the output of this function
a = function();
//now i want output
cout << "the result is : " << a;
}
Is it possible?
EDIT:
The function is in an external library.
Using only standard C++ where no dup-like functions exist, you could open a temporary std::FILE and std::swap with stdout.
#include <cerrno>
#include <cstring>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
// extern "C" int function(); // an assumption
// A helper class to temporarilly redirect the output to stdout to a file and to read
// the content of the file afterwards.
class BufferStdout {
public:
// the collector string is used for collecting the output to stdout
BufferStdout (std::string& collector) :
m_collector(collector),
fp(std::fopen("output.txt", "w"))
{
if(fp == nullptr) throw std::runtime_error(std::strerror(errno));
std::swap(stdout, fp); // swap stdout and the temp file
}
~BufferStdout () {
std::swap(stdout, fp); // swap back
std::fclose(fp);
// read the content of the temp file into m_collector
if(std::ifstream is("output.txt"); is) {
m_collector.append(std::istreambuf_iterator<char>(is),
std::istreambuf_iterator<char>{});
}
std::remove("output.txt"); // cleanup
}
private:
std::string& m_collector;
std::FILE* fp;
};
int main() {
std::string collector; // the string that will contain the output from function()
int a;
{
BufferStdout foo(collector);
a = function();
}
std::cout << "the result is : " << a << '\n';
std::cout << "Collected from function():\n";
std::cout << collector << '\n';
}
Yes it is generally possible but a bit complicated, a similar question is in Suppress output to cout from linked library
In addition to you can redirect stdout before invoking the shared library function and then redirect it again after the use of the shared library function in the however this is also a suboptimal solution. Best solution would be to adapt the shared library
// Cpp program to redirect cout to a file
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
fstream file;
file.open("cout.txt", ios::out);
string line;
// Backup streambuffers of cout
streambuf* stream_buffer_cout = cout.rdbuf();
streambuf* stream_buffer_cin = cin.rdbuf();
// Get the streambuffer of the file
streambuf* stream_buffer_file = file.rdbuf();
// Redirect cout to file
cout.rdbuf(stream_buffer_file);
cout << "This line written to file" << endl;
// Redirect cout back to screen
cout.rdbuf(stream_buffer_cout);
cout << "This line is written to screen" << endl;
file.close();
return 0;
}
Note: The above steps can be condensed into a single step
auto cout_buf = cout.rdbuf(file.rdbuf())
// sets couts streambuffer and returns the old
streambuffer back to cout_buf
source : https://www.geeksforgeeks.org/io-redirection-c/
use
fclose(stdout);
with this function you will suppress any printf inside your libraries.
Of course you can not print other stuff inside your software.

c++ loading dylib functions at runtime error

So I'm trying to load a .dylib file at runtime in c++ and calling a function within it. It does not seem to be any problem loading the file but when i try to create a function-pointer to the "print" function it's result is NULL.
Here is my code:
/* main.cpp */
#include <iostream>
#include <string>
#include <dlfcn.h>
#include "test.hpp"
int main(int argc, const char * argv[]) {
std::string path = argv[0];
std::size_t last = path.find_last_of("/");
// get path to execution folder
path = path.substr(0, last)+"/";
const char * filename = (path+"dylibs/libtest.dylib").c_str();
// open libtest.dylib
void* dylib = dlopen(filename, RTLD_LAZY);
if (dylib == NULL) {
std::cout << "unable to load " << filename << " Library!" << std::endl;
return 1;
}
// get print function from libtest.dylib
void (*print)(const char * str)= (void(*)(const char*))dlsym(dylib, "print");
if (print == NULL) {
std::cout << "unable to load " << filename << " print function!" << std::endl;
dlclose(dylib);
return 2;
}
// test the print function
print("Herro Word!");
dlclose(dylib);
return 0;
}
test dylib headerfile
/* test.hpp */
#ifndef test_hpp
#define test_hpp
void print(const char * str);
#endif
the dylib c++ file
#include <iostream>
#include "test.hpp"
void print(const char * str) {
std::cout << str << std::endl;
}
the output when running is:
unable to load /Users/usr/Library/Developer/Xcode/DerivedData/project/Build/Products/Debug/dylibs/libtest.dylib print function!
Program ended with exit code: 2
I am quite new to c++ and have never loaded dylibs before. Any help would be much appreciated!
Try qualifying the print function declaration with extern "C" to get around the name mangling that is likely going on.
Here's a nice article on the topic: http://www.tldp.org/HOWTO/C++-dlopen/theproblem.html (solution discussion on page following)

How do you insert a variable into CreateDirectory()

Is there a way to insert a string variable into CreateDirectory? I want it to create a directory in C: with the name the user has entered. When I do something like
CreateDirectory ("C:\\" << newname, NULL);
My compiler gives me the error "No match for operator<< in 'C:\ << newname'"
This is my code. The problem is in void newgame().
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <mmsystem.h>
#include <conio.h>
using namespace std;
int a;
string newname;
string savepath;
struct game
{
string name;
int checkpoint;
int level;
};
void wait( time_t delay )
{
time_t timer0, timer1;
time( &timer0 );
do {
time( &timer1 );
} while (( timer1 - timer0 ) < delay );
}
void error()
{
cout << "\nError, bad input." << endl;
}
void options()
{
cout << "No options are currently implemented." << endl;
}
void load()
{
cout << "Load a Game:\n";
}
//This is where I'm talking about.
void newgame()
{
cout << "Name your Game:\n";
getline(cin,newname);
cin.get();
game g1;
g1.name=newname;
//I want it to create a dir in C: with the name the user has entered.
//How can I do it?
CreateDirectory ("C:\\" << newname, NULL);
}
//This isn't the whole piece of code, just most of it, I can post the rest if needed
CreateDirectory (("C:\\" + newname).c_str(), NULL);
You can join std::strings with operator+. Or, in your case, you can join a C string to an std::string using operator+, also. The result is an std::string. (Be careful though -- you cannot join two C strings together that way.)
I suspect, however, that CreateDirectory takes a C string, not a std::string, so you'll need to convert it with the .c_str() member.
To use stream insertion, you need to first create a stream:
std::ostringstream buffer;
buffer << "c:\\" << newname;
CreateDirectory(buffer.str().c_str());