i am new to c++ and trying to write a simple function, that saves a string to a file.
The function works, when i pass the full path to fstream, but it doesn't resolve relative paths.
Here is the relevant part of my code
#include <iostream>
#include <fstream>
void writeToFile ()
{
std::fstream fs;
fs.open ("/home/blabla/Documents/test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << " test content";
fs.close();
}
This works fine, but i would like to create the file in the folder, where my program is executed, so i tried this
fs.open ("./test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
I also tried
fs.open ("~/Documents/test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
Neither of them created a new file and i did not get any error message.
I found this post, which suggests, that i can pass relative paths to fstream but only gives windows examples.
How to use fstream objects with relative path?
I work on Linux Mint, the target environment is debian.
I am thankful for any hints or suggestions,
Michael
Your program
#include <iostream>
#include <fstream>
void writeToFile () {
std::fstream fs;
fs.open ("./test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << " test content";
fs.close();
}
int main() {
writeToFile();
}
works perfectly fine for me on Coliru.
As you can see from the ls
output, the file was created
a.out << The executable program
main.cpp << The source
test.txt << The created text file
and cat
at least dumps the content of the file
test content
As mentioned in my comment, a path like ~/Documents/test.txt
is evaluated by the shell, while ./test.txt
should work for openting an existing file, if you're running your program in the same directory where the file exists.
"Neither of them created a new file and i did not get any error message."
You'll never get any kind of error message, if std::fstream::open()
failed for some reason.
You have to check for the stream state after that call, like e.g.
if(!fs) { std::cerr << "Could not open file" << std::endl; }
You may e.g. not have rights to create a file in this directory.
Another option is to use the std::basic_ios::exceptions()
function of std::fstream()
, to trigger an exception when the stream state runs into an error condition.
Relative paths do work with streams. You have two interesting cases though. The tilde (~
) is a special character that some shells interpret. I suspect that fstream doesn't do that interpretation. As to the example of "./test.txt"
, I think the previous comment is correct - that file has been created - it's just not where you expected it.