Open file using full path from file selection dialog

Hi!
I am having trouble with opening file, which was selected from dialog (Win API).
Here is my 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "stdafx.h"
#include <windows.h>
#include <string.h>
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <array>

using namespace std; 




int main()
{
		cout<<"Opening file selection dialog. Please wait..."<<endl;
	OPENFILENAME ofn;       // common dialog box structure
	wchar_t szFile[260];       // buffer for file name
	HWND hwnd;              // owner window
	HANDLE hf;              // file handle
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	wchar_t title[500];  // to hold title
	GetConsoleTitle( title, 500 );
	HWND hwndConsole = FindWindow( NULL, title );
	ofn.hwndOwner = hwndConsole;
	ofn.lpstrFile = szFile;
	ofn.lpstrFile[0] = '\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = L"Text File\0*.txt";
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box. 

if (GetOpenFileName(&ofn)==TRUE) 
    hf = CreateFile(ofn.lpstrFile, 
                    GENERIC_READ,
                    0,
                    (LPSECURITY_ATTRIBUTES) NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    (HANDLE) NULL);

	

	int i=0;

	wcout<<"Selected file: "<<szFile<<endl;


	cout<<"Opening selected file... ";
	for(i=0; i<500; i++){ //here could be szFile.size()... but it causes an error.
		if(szFile[i]=='\\')
			szFile[i]='/';
	};
	
	fstream selectedFile;
	selectedFile.open(szFile);
	if(selectedFile.is_open()){
		cout<<"SUCCEEDED"<<endl;
	} else {
		cout<<"FAILED"<<endl;
	};

	

	cout<<endl;
	system("PAUSE");
	return 0;

}
I'm confused about lines 57 to 59. Why are u changing the backslashes?
For fstream to open a file it has to be of the format:
selectedFile.open("C:\\USERS\\PROJECTS\\myproject.txt"); //the caps don't matter

szFile has no member size() because it's just a char. U already know the length of it to be 260 from line 19
Last edited on
Topic archived. No new replies allowed.