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

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

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.

Get exe name that is currently running (Not the path) [duplicate]

This question already has answers here:
Get path of executable
(25 answers)
Get a file name from a path
(24 answers)
Closed 2 years ago.
hey so i wanted to get name of the exe that is currently running
here is what ive tried doing
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
char filename[ MAX_PATH ];
DWORD size = GetModuleFileNameA( NULL, filename);
if (size)
cout << "EXE file name is: " << filename << "\n";
else
cout << "Could not fine EXE file name.\n";
return 0;
}
but it gets the path of the exe too but i only need the exe name any help?
The first command line argument is the name of the current program
#include <iostream>
#include <string>
#include <windows.h>
#include <algorithm>
int main(int argc, char** argv)
{
if (argc > 0)
std::cout << argv[0] << std::endl;
else {
//some other method has to be used, use OP's suggestion
char filename[ MAX_PATH ];
DWORD size = GetModuleFileNameA( NULL, filename, MAX_PATH);
if (!size) {
std::cout << "Could not fine EXE file name.\n";
return -1;
}
//Remove everything before the last "\"
std::string name = filename;
auto it = std::find(name.rbegin(), name.rend(), '\\'); //escape the escape character
if (it != name.rend()) {
name.erase(name.begin(), it.base());
}
std::cout << filename << std::endl;
}
}

Cannot open text file using ifstream

ifstream fin;
fin.open("‪C:\\Users\\Zach\\Desktop\\input.txt");
if (!fin)
{
cout << "e";
}
e is printing whether I use the full pathway or just input.txt from a resource file
If the file exists, make sure that you have got the path specified correctly. Since you're running on Windows, you can verify the full path to your executable with the following code.
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#define BUFSIZE 4096
std::string getExePath()
{
char result[BUFSIZE];
return std::string(result, GetModuleFileName(NULL, result, BUFSIZE));
}
int main()
{
std::ifstream infile("input.txt");
if (infile.is_open())
{
std::cout << "Success!" << std::endl;
infile.close();
}
else
{
std::cout << "Failed to open input.txt!" << std::endl;
std::cout << "Executable path is ->" << getExePath() << "<-" << std::endl;
}
return 0;
}
This will allow you to verify that your path to the input file is correct, assuming that it's collocated with your executable.
You need to direct output into the ifstream object by using fin << "string"; and not directing to standard out via cout.

gnuplot in c++ - path error [duplicate]

This question already has an answer here:
gnuplot-cpp cannot feed command to pipe
(1 answer)
Closed 8 years ago.
I'm trying to implement the code below from this site:
https://sites.google.com/site/bettereaclone/introduction/gnuplot/c-example-gnuplot-1
Code:
#include <iostream>
#include "gnuplot_i.hpp"
#include <windows.h>
#include <conio.h>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
try
{
Gnuplot g1("lines");
cout << "*** plotting slopes" << endl;
g1.set_title("Slopes\\nNew Line");
cout << "y = x" << endl;
g1.plot_slope(1.0,0.0,"y=x");
cout << "y = 2*x" << endl;
g1.plot_slope(2.0,0.0,"y=2x");
cout << "y = -x" << endl;
g1.plot_slope(-1.0,0.0,"y=-x");
g1.unset_title();
}
catch (GnuplotException ge)
{
cout << ge.what() << endl;
}
return 0;
}
I installed the gnuplot (http://www.gnuplot.info/download.html)
gnuplot_i.hpp file (https://code.google.com/p/gnuplot-cpp/source/browse/trunk/gnuplot_i.hpp)
When I run this code, I get this problem:
The error:
'C:/Program' is not recognized as an internal or external command,
operable program or batch file.
I've no idea why. thanks!!
Looks like path to gnuplot is malformed, not in quotation marks or simply not read properly.
Try forcing the path by uncommenting this line and correcting it to point gnuplot directory on your machine:
// Gnuplot::set_GNUPlotPath("C:/program files/gnuplot/bin/");

Using a C++ .exe with C++ : C++ception [duplicate]

This question already has answers here:
launch an exe/process with stdin stdout and stderr?
(3 answers)
Closed 8 years ago.
I need some help on this subject.
I have a C++ .exe that I want to open with C++ and then write some arguments in the console.
Here is an example of what I want to do:
Lets assume an executable whatsyourage.exe with this code (in reallity, I don't have the corresponding code):
#include <iostream>
using namespace std;
int main()
{
int age = 0;
cout << "What's your age ?" << endl;
cin >> age;
cout << "You are " << age << " year !" << endl;
return 0;
}
and I want to do something like:
int main()
{std::string invit="21";
std::string chemin ="whatsyourage.exe";// in the same library
std::string const command = chemin+" "+ invit;
system(command.c_str());
}
I want to write the age (21).
Can someone please help me?
Here is the answer:
int main()
{std::string invit="21";
std::string chemin ="whatsyourage.exe";
FILE* pipe = _popen(chemin.c_str(), "w");
if (pipe == NULL) {
perror("popen");
exit(1);
}
fputs("30", pipe);// write the age into the pipeline
pclose(pipe); // close the pipe
}
The popen() function from POSIX does what you are looking for. It allows you to execute a program (like system) while getting a file handle on its input/output streams.
For Windows, if popen() is not available, you can use the CreatePipe() & co functions to do the same thing; check out this question for some pointers.
The second snippet you added is good, and the problem is with the first code. In order to handle the command line from a program, you have to define the main as int main(int numberOfArguments, char* arguments[]) (often people use the shorter version - main(int argc, char* argv[]), but you can name the arguments as you wish). Then, if you pass an argument to the function, it will be in argv[1], since argv[0] is always the path to the executable. So the first program should look like this:
int main(int numberOfArguments, char* arguments[])
{
if(numberOfArguments>=2)
cout << "You are " << arguments[1] << " year !" << endl;
else
cout << "Too few arguments passed!" << endl;
return 0;
}