Hi. I am working on a little program that will be able to open files and read them. The problem is that i CANNOT tell the user to manually type the directory and the name of the file ! It would be madness. So i need to use GetOpenFileName dialog...

Now, i have a little problem. This is the code, i used the example from MSDN, my skills in C++ are quite low so i dont really understand the code...

#include <windows.h>
#include <fstream>

int main()
{
printf("declaring...\n");
// Declare
OPENFILENAME ofn;       // common dialog box structure
char szFile[260];       // buffer for file name
HWND hwnd;              // owner window
HANDLE hf;              // file handle

printf("initialising...\n");
// 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.
//
printf("setting...\n");
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;

printf("displaying...\n");
// 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);

printf("\n");
printf("opened. exiting...\n");
printf("...");

return 0;
}

Now, my question is HOW CAN I GET the path and the filename ... lets say i want to printf the path and the filename that i selected with this GetOpenFileName function...
MSDN sais "If the user specifies a file name and clicks the OK button, the return value is nonzero. The buffer pointed to by the lpstrFile member of the OPENFILENAME structure contains the full path and file name specified by the user." ... But how can i get them?

Please help, i am sure this is a simple thing for a C++ expert...

PS: This was compiled with VS.Net. I also tried to compile it in DEV C++, but i get an compile error. I suppose it doesnt work with MS Comdlg32.lib...

Use the strrchr function to search for the last occurrance of the backslash '\' character. If there is no match strrchr returns NULL, that means no path was returned in szFile, and all the contents of szFile is the filename. If there is a match, the contents from the starting position of szFile upto the position returned by strrchr is the path name. The rest is the filename. Try it yourself and post your attempt.

GetOpenFileName will put that information in your szFile buffer. And it should be declared and initializedlike this: char szFile[_MAX_PATH] = {0};

I tried this:

printf(ofn.lpstrFile);
printf("\n");
printf(szFile);

printf("\nFile opened. exiting...\n");
system("PAUSE");

And i got this output:

declaring...
initialising...
setting...
displaying...
C:\Dev-Cpp\NEWS.txt
C:\Dev-Cpp\NEWS.txt
File opened. exiting...
Press any key to continue . . .

:D This means that it's working.
Thank you. And i will use strchr to check if the file is in the same directory.

Another problem, related to this. I saw that everyone has problems with opening and reading files... so do i.
I am using this GetOpenFileName function to select m3u files and load all the music files from that m3u.

// ... blah, blah, more global variables...
OPENFILENAME ofn; // Common dialog box structure.
char szFile[260]; // Buffer for selected file name.
HWND hwnd; // Owner window.
HANDLE hf; // File handle.

// blah, blah, more funtions...
inline void OpenWindow()
{
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;

ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Playlists: m3u.\0*.m3u\0Music Files :mp1, mp2, mp3, wav, ogg.\0*.mp1;*.mp2;*.mp3;*.wav;*.ogg\0";
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);
return;
}

That is the open window function and all important variables are declared global. I call it, then i change the "\" character with "/" character, just to be sure:

for( unsigned int i=0; i < strlen(szFile); i++ )
     if (szFile[i] == 92) szFile[i] = 47; // Replace '\' with '/'.

than i call this function:

inline void m3u_to_PlayList()
{
fstream F; F.open(szFile, ios::in);
F.clear(); F.seekp(0, ios::beg);
char Line[260]="0";

while( F.get(Line, 260) ) // Load m3u data into the Playlist.
    { /* This loop should do something similar to printing the lines
       from the m3u file. I used a message box as an example. */
	MessageBox(NULL, Line, "msg", MB_OK);
	F.get();
    }

F.close();
MessageBox(NULL, "Loop done.", "msg", MB_OK);

return;
}

Now, the problem is that the file is NEVER opened... I ALWAYS get a blank message window when the code from m3u_to_playlist, (line 14 here) is executed.
The interesting part in m3u_to_playlist is that if i change "fstream F; F.open(szFile, ios::in);" (line 4 here) with "fstream F; F.open("D:/mylist.m3u", ios::in);", the file is opened correctly...

So now i ask: what is the difference between szFile, the string i get from GetOpenFileName function, and my "D:/mylist.m3u" string ?? I tried everything, i tried the stringname.length(), i compared them in messagebox-es... They are completely THE SAME.
I can't figure it out. All my project is stuck, blocked because of this tiny problem...

Pliiiiiiiz help... :sad:

Hi,

Did you found a solution for this problem ? I believe I am facing a similar problem.

regards

Another problem, related to this. I saw that everyone has problems with opening and reading files... so do i.
I am using this GetOpenFileName function to select m3u files and load all the music files from that m3u.

....
Now, the problem is that the file is NEVER opened... I ALWAYS get a blank message window when the code from m3u_to_playlist, (line 14 here) is executed.
The interesting part in m3u_to_playlist is that if i change "fstream F; F.open(szFile, ios::in);" (line 4 here) with "fstream F; F.open("D:/mylist.m3u", ios::in);", the file is opened correctly...

So now i ask: what is the difference between szFile, the string i get from GetOpenFileName function, and my "D:/mylist.m3u" string ?? I tried everything, i tried the stringname.length(), i compared them in messagebox-es... They are completely THE SAME.
I can't figure it out. All my project is stuck, blocked because of this tiny problem...

Pliiiiiiiz help... :sad:

The main problem with that code is that mp3 files are binary files and attempting to read them as text files won't work. Here is a working program that is just plain-jane c++.

#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// ... blah, blah, more global variables...
OPENFILENAME ofn; // Common dialog box structure.
char szFile[260]; // Buffer for selected file name.
HWND hwnd; // Owner window.
HANDLE hf; // File handle.

// blah, blah, more funtions...
inline void OpenWindow()
{
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Playlists: m3u.\0*.m3u\0Music Files :mp1, mp2, mp3, wav, ogg.\0*.mp1;*.mp2;*.mp3;*.wav;*.ogg\0";
ofn.nFilterIndex = 2;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

// Display the Open dialog box. 
GetOpenFileName(&ofn);
//    hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, (LPSECURITY_ATTRIBUTES) NULL,
//        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
return;
}


inline void m3u_to_PlayList()
{
ifstream F;
char Line[260] = {0};
F.open(szFile, ios::binary);
if( F.is_open())
{
    while( F.read(Line, sizeof(Line)) ) // Load m3u data into the Playlist.
    { /* This loop should do something similar to printing the lines
       from the m3u file. I used a message box as an example. */


        sz = F.gcount(); // get number of characters read
        cout.write(Line,sz); // write data to the screen
    }
    F.close();
}

cout << "\n\nLoop done\n";
return;
}

int main()
{
    OpenWindow();
    m3u_to_PlayList();
    return 0;
}

Hi. I am working on a little program that will be able to select *.txt files to process the information in them.
I have a problem using a browse source in C++. The errors displayed are:
browse-source.cpp
j:\browse-source.cpp(30) : error C2065: 'SearchFolder' : undeclared identifier
j:\browse-source.cpp(46) : error C2373: 'SearchFolder' : redefinition; different type modifiers
j:\browse-source.cpp(76) : error C2065: 'sprintf' : undeclared identifier
j:\browse-source.cpp(88) : error C2065: 'm_listbox_hwnd' : undeclared identifier
j:\browse-source.cpp(90) : error C2065: 'and' : undeclared identifier
j:\browse-source.cpp(90) : error C2146: syntax error : missing ';' before identifier 'put'
j:\browse-source.cpp(90) : error C2065: 'put' : undeclared identifier
j:\browse-source.cpp(90) : error C2146: syntax error : missing ';' before identifier 'your'
j:\browse-source.cpp(90) : error C2065: 'your' : undeclared identifier
j:\browse-source.cpp(90) : error C2146: syntax error : missing ';' before identifier 'own'
j:\browse-source.cpp(90) : error C2065: 'own' : undeclared identifier
j:\browse-source.cpp(90) : error C2146: syntax error : missing ';' before identifier 'code'
j:\browse-source.cpp(90) : error C2065: 'code' : undeclared identifier
j:\browse-source.cpp(92) : error C2059: syntax error : '}'
j:\browse-source.cpp(94) : error C2228: left of '.FindNextFileA' must have class/struct/union type

//Call Browse Folder Window, Search Entire Folder and all sub-folders for desired file(s).
//This function was written by Jered McFerron ( JHawkZZ ). It's a pretty handy thing to add to your
//windows application, and I decided to publish this because I've seen many requests and few replies.


//Some parts of the Browse Folder dialog code taken from http://www.mvps.org/vcfaq/sdk/20.htm.


#include <windows.h>
#include <shlobj.h>
#include <string.h>

//BROWSE FOLDER - Opens a browse folder dialog.
void	BrowseFolder( void )
{
	TCHAR path[MAX_PATH];
	BROWSEINFO bi = { 0 };
	bi.lpszTitle = ("All Folders Automatically Recursed.");
	LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
	
	if ( pidl != 0 )
	{
		// get the name of the folder and put it in path
		SHGetPathFromIDList ( pidl, path );

		//Set the current directory to path
		SetCurrentDirectory ( path );
	
		//Begin the search
		SearchFolder( path );


		// free memory used
		IMalloc * imalloc = 0;
		if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
		{
			imalloc->Free ( pidl );
			imalloc->Release ( );
		}
	}
}//BROWSE FOLDER


//SEARCH FOLDER - Searches folder and all sub-folders for audio files.
void	SearchFolder( TCHAR * path )
{
		//Declare all needed handles
		WIN32_FIND_DATA FindFileData;
		HANDLE			hFind;

		TCHAR	filename[ MAX_PATH + 256 ];
		TCHAR	pathbak[ MAX_PATH ];

		//Make a backup of the directory the user chose
		strcpy( pathbak, path );

		//Find the first file in the directory the user chose
		hFind = FindFirstFile ( "*.*", &FindFileData );

		//Use a do/while so we process whatever FindFirstFile returned
		do
		{
			//Is it valid?
			if ( hFind != INVALID_HANDLE_VALUE )
			{
				//Is it a . or .. directory? If it is, skip, or we'll go forever.
				if ( ! ( strcmp( FindFileData.cFileName, "." ) ) || ! ( strcmp( FindFileData.cFileName, ".." ) ) )
				{
					continue;
				}

				//Restore the original directory chosen by the user
				strcpy( path, pathbak );

				//Append the file found on to the path of the directory the user chose
				sprintf( path, "%s\\%s", path, FindFileData.cFileName );

				//If SetCurrentDirectory Succeeds ( returns 1 ) the current file is a directory. Pause this function,
				//and have it call itself. This will begin the whole process over in a sub directory.
				if ( ( SetCurrentDirectory( path ) ) )
				{
					SearchFolder( path );
				}
				
				 //Otherwise right here is where you need to insert what you want to do. 
			         //As an example let's add the filename to a list box.
          			 //INSERT WHAT YOU WANT DONE BELOW!
           			 SendMessage( m_listbox_hwnd, LB_ADDSTRING, 0, path ); //<--INSERT WHAT YOU WANT DONE HERE!
				//m_listbox_hwnd is just an example handle to a fake listbox. Delete all this
				and put your own code.
	
			}
		}
		while ( FindNextFile ( hFind, &FindFileData ) && hFind != INVALID_HANDLE_VALUE );

		FindClose ( hFind );
}//SEARCH FOLDER

PS: I'm using visual c++ 6.0, but i'm not good at C++

Please help.

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.