0

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

  • You are trying to open another file after opening the first one: `myfile.open ("hosts.txt", std:: ios::app);` Why is that there? – walnut Dec 08 '19 at 02:07
  • Totally right, forgot to remove that. That solved my issue, so if you'd like to post an official answer I can select it for you. Thanks again. – eric saddy Dec 08 '19 at 05:34
  • I voted to close it as typo instead. I don't think this question will be helpful to others. – walnut Dec 08 '19 at 05:36
  • Okay, thanks for your help regardless. – eric saddy Dec 08 '19 at 05:37

0 Answers0