I keep getting this error and have no idea how to fix it because I don't see anything wrong with my code.
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
void file_create(std::string name) {
std::ifstream file(name);
if (file.is_open()) {
file.close();
std::cout << "File already exists..." << std::endl;
main();
}
else {
file.close(); std::ofstream newFile(name);
if (newFile.is_open())
std::cout << GREEN "New file successfully created..." << RESET << std::endl;
else
std::cout << RED "File could not be created" << RESET << std::endl;
newFile.close();
}
}
int main() {
}
CodePudding user response:
The main function is not intended to be invoked from your code. It is also a nonsense since it is called automatically when program starts. But if you need some alternative main to be invoked upon some condition, you can call it inside your main function
...
int alternative_main()
{
place your program there
}
...
void file_create(std::string name) {
...
if (file.is_open()) {
...
alternative_main()
}
else {
...
}
}
Suppose your main looks like this
int main() {
file_create("myfile");
}
CodePudding user response:
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
//use this instead of repetitively using std all the time
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
void file_create(string name) {
ifstream file(name);
if (file.is_open()) {
file.close();
cout << "File already exists..." << endl;
return 0;
}
else {
file.close();
ofstream newFile(name);
if (newFile.is_open())
cout << GREEN "New file successfully created..." << RESET << endl;
else
cout << RED "File could not be created" << RESET << endl;
newFile.close();
}
}
int main() {
string name;
cin>>name;
file_create(name);
}
try using this way...