Home > OS >  How to get fstream to save to any windows desktop that opens the .exe in c
How to get fstream to save to any windows desktop that opens the .exe in c

Time:11-06

I'm making a program for my brother that will display 50,000 proxie variations and will save them all to a .txt.

How can I make it so any windows machine that uses this code will get the .txt to save to the desktop.

Here's what I have:

fstream file;
    file.open("proxies.txt", ios::out);
    string line;

    streambuf* stream_buffer_cout = cout.rdbuf();
    streambuf* stream_buffer_cin = cin.rdbuf();

    streambuf* stream_buffer_file = file.rdbuf();

    cout.rdbuf(stream_buffer_file);

    
    for (int i = 1; i < 50001; i  )
    {
        cout << n1 << i << n2 << "\n";
    }

    file.close();

Thanks for any help.

CodePudding user response:

If I get what you are asking you just need to replace "proxies.txt" with an absolute path to a file in the desktop folder. You can get the desktop directory with the Win32 call SHGetFolderPath and put the path together using the standard (C 17) file system calls if you want, as below:

#include <iostream>
#include <filesystem>
#include <fstream>
#include <shlobj_core.h>

namespace fs = std::filesystem;

std::string desktop_directory() {
    char path[MAX_PATH   1];
    if (SHGetFolderPathA(HWND_DESKTOP, CSIDL_DESKTOP, NULL, 
            SHGFP_TYPE_DEFAULT, path) == S_OK) {
        return path;
    } else {
        return {}; // I'm not sure why this would fail...
    }
}

int main() {

    std::fstream file;
    auto desktop_path = fs::path(desktop_directory()) / "proxies.txt";
    file.open(desktop_path, std::ios::out);

    // ...

    file.close();
    return 0;
}
  • Related