How to save the created txt file to a specified path? For example to C:\ Drive. When the code creates a file it saves to the workspace folder of the project. Do I have to set the directory to C:\? I tried using SetCurrentDirectoryA function but does not change to the specified directory.

This is one of the ways I tried:

void createFile(){

    ofstream file("C:\\sample.txt");

    file.close();
}

Recommended Answers

All 5 Replies

Probably need to add some info, os platform, bitness etc...

To me, that looks like should create file in C root, but if windows and vista+ you must invoke admin to create file there.

If I'm wrong, try ftream.

fstream does not work either :(

I have seen some examples and that is how they stored the file to C drive.

Any other options?

Probably need to add some info, os platform, bitness etc...

Using ofstream file("C:\\sample.txt"); should work, unless you do not have to permissions to create a file in the C:\\ directory.

In general, in C++, if you want more control over the file-system (folders, files, etc.), you need to resort to a library for that (at least, until it becomes standard, probably in C++14, I think). You can use the Boost.FileSystem library, or any other file-system manipulation library (e.g., in Qt).

Otherwise, you will have to use API functions directly, such as Win32 API functions (Windows).

But again, your program will only have the file permissions of the user account it runs under. If you need to read / write files in admin-only folders, you will have to run the program with administrator rights.

Probably need to add some info, os platform, bitness etc...

Windows 8

Using ofstream file("C:\sample.txt"); should work, unless you do not have to permissions to create a file in the C:\ directory.

Yup ofstream should work. At my uni lab this way worked but at my home laptop it just cant seem to write in C:\ drive. I went to check the C:\ drive properties and saw as a User I can not write to C:\ drive, however, as the administrator I had permissions to write(of course). So I ran the MSVC IDE as admin and voila it worked.

Thank you Suzie and Mike :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.