How to select a file from directory in C++

I know how to open a specific files by using

ifstream infile("something.txt");

but how do you let the user select an arbitrary file from the working directory?

thanks!

-waka
bump
Not even a whole minute before a bump, that must be a record. The "std::ifstream" object takes a char array for the first argument. So prompt the user for the file name, store that to some variable and then pass that variable to constructor. Or am I miss understanding you?
closed account (j3Rz8vqX)
Prompt the user for a string.
insert the string into where the solid double quotes were and add .c_str().

Example:
ifstream infile(something.c_str());

http://www.cplusplus.com/reference/fstream/ifstream/open/
Thanks for the replies!

However, what I am looking for is for the user to select a file from the directory (like an open file window) and select the file with the click of the mouse.

Anything like that possible?

Thanks!!

-Waka
Windows code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Example to ask for a filename
// Copies the file to the standard output
// (Prefers .txt files, but you can chose anything, of course)
//
#include <fstream>
#include <iostream>
#include <string>

#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

int main()
  {
  using namespace std;
  string filename( 0, MAX_PATH );
  
  OPENFILENAME ofn;
  ZeroMemory( &ofn,  sizeof( ofn ) );
  ofn.lStructSize  = sizeof( ofn );
  ofn.lpstrFilter  = "Text Files" "\0"  "*.TXT" "\0" 
                     "Any File"   "\0"  "*.*"   "\0";
  ofn.nFilterIndex = 1;
  ofn.lpstrFile    = (char*)filename.c_str();
  ofn.nMaxFile     = MAX_PATH;
  ofn.Flags        = OFN_CREATEPROMPT | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
  
  if (!GetOpenFileName( &ofn ))
    {
    cerr << "You must select a file!\nQuitting.\n";
    return 1;
    }
    
  ifstream f( ofn.lpstrFile );
  if (!f)
    {
    cerr << "I could not open " << ofn.lpstrFile << "\nQuitting.\n";
    return 1;
    }
    
  cout << ofn.lpstrFile << ":\n";
  cout << f.rdbuf();
  f.close();
  
  return 0;
  }

Enjoy.
Looks promising but it crashes at

if (!GetOpenFileName( &ofn ))

.

FYI i am using DEV C++ and I just ran the code you sent.
closed account (j3Rz8vqX)
You need to add the lib.

A codeblocks installed mingw: libcomdlg32.a

A codeblocks installation may be at:
STUFF\CodeBlocks\MinGW\lib\libcomdlg32.a


Sort of feeding you to the sharks, but another example would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <windows.h>

char* myFunction(){
    OPENFILENAME ofn;
    char *FilterSpec ="Object Files(.obj)\0*.obj\0Text Files(.txt)\0.txt\0All Files(.)\0*.*\0";
    char *Title ="Open....";
    char szFileName[MAX_PATH];
    char szFileTitle[MAX_PATH];

    *szFileName = 0; *szFileTitle = 0;

    /* fill in non-variant fields of OPENFILENAME struct. */
    ofn.lStructSize       = sizeof(OPENFILENAME);
    ofn.hwndOwner         = GetFocus();
    ofn.lpstrFilter       = FilterSpec;
    ofn.lpstrCustomFilter = NULL;
    ofn.nMaxCustFilter    = 0;
    ofn.nFilterIndex      = 0;
    ofn.lpstrFile         = szFileName;
    ofn.nMaxFile          = MAX_PATH;
    ofn.lpstrInitialDir   = "."; // Initial directory.
    ofn.lpstrFileTitle    = szFileTitle;
    ofn.nMaxFileTitle     = MAX_PATH;
    ofn.lpstrTitle        = Title;
    ofn.lpstrDefExt   = 0;//I've set to null for demonstration

    ofn.Flags             = OFN_FILEMUSTEXIST|OFN_HIDEREADONLY;

    if (!GetOpenFileName ((LPOPENFILENAME)&ofn))
    {
        return ("NULL"); // Failed or cancelled
    }
    else
    {
      return szFileName;
    }
}
int main(){
    std::cout<<"File location\\name: \n"<<myFunction()<<std::endl;
    return 0;
}


More variance to play with...

Non mingw folks may need alternative dependencies:
#include <commdlg.h> and link with comdlg32.lib


Edit x 3 to improve behavior of code, apologies..
Last edited on
Do I need to use codeblocks? Is it possible to do this with just Dev C++?
You can do it from notepad, if you want. This is straight-up Windows API.
@ OP: Duoas is not trying to be obscure here, he wants to illustrate that an IDE is basically a special purpose text editor. To further exemplify this point, I believe the third or fourth most popular development environment on our little forum is VIM.
/me double-takes

Holy cow! Really?

I mean, I like vim, but I didn't think that people would actually develop too much with it. I only use it for quick, one-off edits, when it would take more time and effort to fire up my regular development environment.
My assessment was based off how steep of a drop off there would be after MSVS and Code::Blocks the next candidate is possibly netbeans or unfortunately dev-cpp. Maybe I'm over estimating the number of POSIX contributors we have here but what other dev environments do you ever hear mentioned?

AFTERTHOUGHT: Notepad++ might be another runner up.

EDIT: I haven't developed the attention span for cross-compiling yet and who ever thought that relative paths in *nix are anything like they are in Windows needs to have their head checked. For these reasons I can barely use Code::Blocks in *nix so VIM is my personal goto (pun intended) in alternative settings.
Last edited on
Topic archived. No new replies allowed.