-1

fstream does not work for writing files in Linux, using the following code:

#include <iostream>                     //for console input and output
#include <fstream>                      //for file input and output

int main(int argc, char **argv) {
    std::ofstream outFile("~/test_ws/src/data_logger/src/myFile.txt", std::ios::out | std::ios::binary);
    outFile.open("~/test_ws/src/data_logger/src/myFile.txt", std::ios::out | std::ios::binary);
    if(outFile.is_open()) {
        outFile << "Writing whether you like it or not.\n";
        std::cout << "YES!\n";
    } else std::cout << "Nope!\n";
    outFile.close();
}

What is the problem? Alternatively, is there another C++ API that I can use for writing files in Linux?

JBentley
  • 6,099
  • 5
  • 37
  • 72
Raisintoe
  • 201
  • 1
  • 4
  • 11
  • 6
    _"fstream does not work for writing files in Linux"_ Huh what please?? Of course that works well in any platform OS. Your error situation might be something else that you didn't tell us. – πάντα ῥεῖ Dec 17 '18 at 23:42
  • 1
    I edited the question to instead ask why the code isn't working, but also left your [XY question](https://meta.stackexchange.com/q/66377/214708) intact. Hint: for future questions, it is usually best not to make assumptions (e.g. instead of "why doesn't the `foo` function work in `bar` language?", try "why is my code using the `foo` function not working?"). – JBentley Dec 17 '18 at 23:51
  • Possible duplicate of https://stackoverflow.com/questions/48759799/how-to-replace-the-home-directory-with-a-tilde-linux also https://stackoverflow.com/questions/31035974/use-shell-symbols-in-directory-path also https://stackoverflow.com/questions/52255940/reference-linux-username-in-string-to-open-file – Galik Dec 18 '18 at 00:07

1 Answers1

7

fstream & co. work perfectly well on Linux. The problem with your code is that you are using ~, which isn't a "real" path as recognized by C++ fstream and in general lower level system calls, but it generally works from the command line as it is expanded by the shell.

If you want your program to perform shell-like path expansion, you can call the wordexp function; mind you, in many years of working on Linux I don't think I ever needed that, as generally paths come "from the outside" as command arguments, already expanded by the shell (and that's the general assumption, not to be broken to avoid doubly-expanding stuff; wordexp has its typical usage when expanding paths e.g. in configuration files).

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299