Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

c++ - fstream doesn't resolve path

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...