Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
336 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...