attempting to append text to a (fake) host file in C++ 11 - c++

I'm essentially attempting to append text to a host text file on MacOS (mojave) and it's not working.
I created a fake host file located at: /public/etc/hosts (real host file is private/etc/hosts)
and all I'd like to do in this scenaro is append the word "data" to the end of the hosts.txt file. When I run the application, it says the the file opens successfully, but the file remains unmodified after execution.
Code:
#include <iostream>
#include <fstream>
int main(int argc, const char * argv[]) {
std::ofstream myfile;
myfile.open("/public/etc/hosts.txt", std::ios::app);
if(!myfile.is_open()){
std::cout << "File could not be opened";
} else {
myfile.open ("hosts.txt", std:: ios::app);
myfile << "data";
std::cout << "Host file has been modified /n";
myfile.close();
}
return 0;
}
the above returns: Host file has been modified
here is file structure:
hosts.txt location on MacOS mojave
If I'm not mistaken the word "data" should be appended to the hosts.txt file after execution and since file.is_open checks out I'm really not sure why this isn't working.
Any insight is appreciated, thanks

Related

C++ Read File being wiped at start of program using ofstream

I'm trying to read a text file and output the contents. It's just I can't seem to find the right method and the ones I've used (including this one), seems to wipe the text file. The code:
std::string Line;
std::ifstream File("Account.txt");
if (File.is_open()) {
while (getline(File, Line)) {
std::cout << Line << std::endl;
}
}
else {
std::cout << "Unable to open File" << std::endl;
}
File.close();
I'm also using:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
I'm using this code (below) every time the program runs to create the file which might be the error, if so can anyone recommend a way to create the file only if it doesn't already exist
std::ofstream File("Account.txt");
File.close();
Your file is being wiped by your file creating code.
std::ofstream File("Account.txt");
File.close();
To create a file without wiping existing contents try this
std::ofstream File("Account.txt", std::ios_base::app);
File.close();

Can't open file properly in C++

I'm trying to read each line from a .geom file and save that in a string.
The user shall input the correct (absolute) filepath and then, until now, should get the content of the .geom file printed out on the console.
The problem is that under every circumstance it seems impossible to open the file via my c++ program.
Everytime I check if the file is opened via is_open() it responds with false.
The program, my IDE and the .geom file are all on the same drive and i am currently using windows. The IDE im using is Codeblocks and the executable is build in it.
This is my complete code until now:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//a function to check if the given file has the .geom extension
bool isGeom(string file){
if(file.substr(file.find_last_of(".") + 1) == "geom") {
return true;
} else {
return false;
}
}
//main func
int main()
{
string filepath, geomInput, line;
cout << "----- GeomView2obj -----" << endl;
cout << "Please enter a valid file path to a .geom file to convert it to an .obj file: \n" << endl;
//get file path by user
getline(cin, filepath);
//declare stream and open file if possible
ifstream geomFile (filepath.c_str());
if(!geomFile.is_open()){
cout << "\nERR: The given file path is invalid or the file does not exist!" << endl;
return 1;
}
if(!isGeom(filepath)){
cout << "\nERR: The given file is not a .geom file!" << endl;
return 1;
}
//read chars from geom file
while(getline(geomFile, line)){
geomInput.append(line + "\n");
}
//print string --- DELETE
cout << geomInput;
geomFile.close();
return 0;
}
I also tried to first declare my ifstream and then opening the file.
I also turned the user input off and entered an absolute path where every folder was seperated with two backslashes \\ instead of one.
I also copied the file to the folder the compiled program lies in and giving the program a relative path to the file as an input, but that also did not help.
Any form of help is much appreciated!

ifstream says it opened a file but the file doesnt open

I am using visual studio 2017
I am new to c++ and here I tried to open a txt file, and confirming that it was opened.
#include <iostream>
#include <fstream>
#include <String>
using namespace std;
int main()
{
ifstream infile;
string text;
infile.open("C:\\Users\\gab_a\\source\\repos\\one\\testing.txt");
if (!infile.is_open()) {
cerr << "Specified file could not be found ";
exit(1);
}
else {
cout << "Opened file ";
infile >> text;
cout << text;
}
return 0;
}
it says that it opened it, and it even read the text that was inside the file, but the actual file isn't opening, I even put the file in the same directory as the project. There are also no errors, so why isn't my file opening?
What you're doing is reading the data from the file into a stream. This is not the same as executing a program to open the file. To do that is generally OS specific, but if you're on Windows you can use ShellExecute or CreateProcess. I do suggest you brush up on your C++ a bit - no offense intended

Ifstream cannot open file with amdinistrator rights

I used this code to try to open and read the file (not empty), but ifstream did not work - it could not open the file: I addded the check on file opening and it showed, that ifstream even did not (could not) open the file.
I gave administrator rights to the program, but ifstream still could not read the file.
I also tried to find a path, where ifstream would read this file, but I did not success, and at last I tried to open file using the absolute path - but result is the same.
The file is situated in the root folder of the program, but I placed it everywhere and nothing changed.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string s;
ifstream file("fix.txt");
if (file)
cout << "SUCCESSFULL OPENING" << endl;
while (getline(file, s)) {
cout << s << endl;
s += "+";
cout << s << endl;
}
file.close();
return 0;
}
You may have access to a more detailed error code by activating exceptions on the stream via
file.exceptions(std::ios_base::failbit);
Then, you get more details by writing
try {
file.open("fix.txt");
}
catch(std::ios_base::failure& f) {
// f.what() contains a message, f.code() returns a std::error_code
}

Windows drag and drop problem with console app

I have a program that creates a file and writes to it using ofstream. I need the program to be able to parse command line parameters later on. But for some reason, it does not create a file when I drag-and-drop a file onto the compiled executable, even if the program doesn't involve any command line parameters at all. If the executable is run normally, it works. So I'm left totally confused. Here is the source:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
ofstream outfile;
outfile.open("test.txt");
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Does anybody have any ideas? I appreciate any help.
You are not using the command line arguments at all. Recode your main() method to look like this:
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Usage: blah.exe file" << endl;
return 1;
}
ofstream outfile;
outfile.open(argv[1]);
if(outfile.is_open())
{
outfile << "Test";
outfile.close();
}
else cout << "Unable to open file";
return 0;
}
Be careful what you drop, your code rewrites the file contents.
The following code does what the OP wants:
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char ** argv )
{
cout << argv[1] << endl;
ofstream outfile;
outfile.open("testzzzzzzz.txt");
if(outfile.is_open())
{
outfile << "Testzzzzz";
outfile.close();
cout << "wrote file"<< endl;
}
else cout << "Unable to open file";
string s;
getline( cin, s );
return 0;
}
It allows drag and drop, but doesn't use the dropped file name in the file open. When you drop a file in it, you get the message
"wrote file"
Unfortunately, at the moment I have no idea where it wrote the file - not in the current directory, definitely. Just going to do a search...
Edit: It creates it in your Documents and Settings directory. So to put it in the current directory, you probably need to explicitly prefix it with "./", but I havent't tested this - I leave it as an exercise for the reader :-)
Since you have not specified a path, the file, test.txt, will be saved to the default path. Just bring up a command prompt (i.e. run cmd.exe) and the command prompt will show you the default path. The file should be in this directory.
You can change the default path by editing the HOMEDRIVE & HOMEPATH environment variables.
Also, you should note the other answers. You should be using argc/argv to specify the output file.
you haven't specified a path for "test.txt" so it will try and create that file in the current working directory of the executable. This will be different when the exe is invoked by dropping a file on it than it is when you run the program normally.
Try giving "test.txt" a full path and see if that works.
edit:
To write your output file to the path that contains the exe, you would use
GetModuleFileName(NULL, ...) to the the full path of the exe,
then PathRemoveFileSpec to strip off the exe name, leaving just the exe path then
PathCombine to append test.txt to the exe path