Using ifstream won't open a file after being selected using OPENFILENAME

Basically, I am trying to let the user select a file given a selection box and given that users input, I want to open their selected .txt file as an ifstream and read from it. The file will not open for some strange reason and I have tried everything I have thought of. Any help would be greatly appreciated, thanks!

Here is the bit of 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
        OPENFILENAME ofn;       // common dialog box structure
	char szFile[260];       // buffer for file name
	HWND hwnd = NULL;              // owner window
	HANDLE hf;              // file handle

	// Initialize OPENFILENAME
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = hwnd;
	ofn.lpstrFile = szFile;
	// Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
	// use the contents of szFile to initialize itself.
	ofn.lpstrFile[0] = '\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
	// 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);

		string filename = "";
		int i=0;
		while (szFile[i] != 0)
		{
			if (szFile[i] == '\\')
			{
				filename += '\\';
			}
			filename += szFile[i++];
		}

		ifstream rankfile;
		rankfile.open(filename.c_str());
		if (rankfile.is_open())              // WILL NOT OPEN!
		{
			while (getline(rankfile, player))
			{
				rankings->push_back(player);
			}
			rankfile.close();
		}
	}
Last edited on
And why do you have this code?
1
2
3
4
5
6
7
8
9
		int i=0;
		while (szFile[i] != 0)
		{
			if (szFile[i] == '\\')
			{
				filename += '\\';
			}
			filename += szFile[i++];
		}


Have you looked at the name of the file that you're trying to open?
I have that in order to set the string filename as the path to the file. In the code above, I changed the single '\' character into '\\' each time it appears, which is needed to open the file correctly, right? I've tried it without that piece of code as well using just the '\' characters in the file name but it still doesn't open the file. I have looked at the file name and it matches exactly what the user selects from the window which is causing my confusion.
Last edited on
The problem is that you already opened the file using exclusive access with CreateFile().

Why do you do that ? It is absolutely not needed. If for some reason you insist on doing so then pass at least FILE_SHARE_READ flag.
Topic archived. No new replies allowed.