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
228 views
in Technique[技术] by (71.8m points)

Write a file in a specific path in C++

I have this code that writes successfully a file:

    ofstream outfile (path);
    outfile.write(buffer,size);
    outfile.flush();
    outfile.close();

buffer and size are ok in the rest of code. How is possible put the file in a specific path?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Specify the full path in the constructor of the stream, this can be an absolute path or a relative path. (relative to where the program is run from)

The streams destructor closes the file for you at the end of the function where the object was created(since ofstream is a class).

Explicit closes are a good practice when you want to reuse the same file descriptor for another file. If this is not needed, you can let the destructor do it's job.

#include <fstream>
#include <string>

int main()
{
    const char *path="/home/user/file.txt";
    std::ofstream file(path); //open in constructor
    std::string data("data to write to file");
    file << data;
}//file destructor

Note you can use std::string in the file constructor in C++11 and is preferred to a const char* in most cases.


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

...