944,129 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 24502
  • C++ RSS
Mar 7th, 2007
0

Open Files with GetOpenFileName

Expand Post »
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...

C++ Syntax (Toggle Plain Text)
  1. #include <windows.h>
  2. #include <fstream>
  3.  
  4. int main()
  5. {
  6. printf("declaring...\n");
  7. // Declare
  8. OPENFILENAME ofn; // common dialog box structure
  9. char szFile[260]; // buffer for file name
  10. HWND hwnd; // owner window
  11. HANDLE hf; // file handle
  12.  
  13. printf("initialising...\n");
  14. // Initialize OPENFILENAME
  15. ZeroMemory(&ofn, sizeof(ofn));
  16. ofn.lStructSize = sizeof(ofn);
  17. ofn.hwndOwner = hwnd;
  18. ofn.lpstrFile = szFile;
  19. //
  20. // Set lpstrFile[0] to '\0' so that GetOpenFileName does not
  21. // use the contents of szFile to initialize itself.
  22. //
  23. printf("setting...\n");
  24. ofn.lpstrFile[0] = '\0';
  25. ofn.nMaxFile = sizeof(szFile);
  26. ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
  27. ofn.nFilterIndex = 1;
  28. ofn.lpstrFileTitle = NULL;
  29. ofn.nMaxFileTitle = 0;
  30. ofn.lpstrInitialDir = NULL;
  31. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
  32.  
  33. printf("displaying...\n");
  34. // Display the Open dialog box.
  35. if (GetOpenFileName(&ofn)==TRUE)
  36. hf = CreateFile(ofn.lpstrFile, GENERIC_READ,
  37. 0, (LPSECURITY_ATTRIBUTES) NULL,
  38. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
  39. (HANDLE) NULL);
  40.  
  41. printf("\n");
  42. printf("opened. exiting...\n");
  43. printf("...");
  44.  
  45. return 0;
  46. }

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...
Last edited by Prahaai; Mar 7th, 2007 at 5:37 am.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
Prahaai is offline Offline
59 posts
since May 2005
Mar 7th, 2007
0

Re: Open Files with GetOpenFileName

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.
Moderator
Reputation Points: 572
Solved Threads: 115
Mentally Challenged Mod.
WolfPack is offline Offline
1,559 posts
since Jun 2005
Mar 7th, 2007
0

Re: Open Files with GetOpenFileName

GetOpenFileName will put that information in your szFile buffer. And it should be declared and initializedlike this:

char szFile[_MAX_PATH] = {0};
Last edited by Ancient Dragon; Mar 7th, 2007 at 8:50 am.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2283
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,961 posts
since Aug 2005
Mar 7th, 2007
0

Re: Open Files with GetOpenFileName

I tried this:

C++ Syntax (Toggle Plain Text)
  1.  
  2. printf(ofn.lpstrFile);
  3. printf("\n");
  4. printf(szFile);
  5.  
  6. printf("\nFile opened. exiting...\n");
  7. system("PAUSE");

And i got this output:

C++ Syntax (Toggle Plain Text)
  1.  
  2. declaring...
  3. initialising...
  4. setting...
  5. displaying...
  6. C:\Dev-Cpp\NEWS.txt
  7. C:\Dev-Cpp\NEWS.txt
  8. File opened. exiting...
  9. Press any key to continue . . .

This means that it's working.
Thank you. And i will use strchr to check if the file is in the same directory.
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
Prahaai is offline Offline
59 posts
since May 2005
Mar 13th, 2007
0

Big Problem

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.

C++ Syntax (Toggle Plain Text)
  1.  
  2. // ... blah, blah, more global variables...
  3. OPENFILENAME ofn; // Common dialog box structure.
  4. char szFile[260]; // Buffer for selected file name.
  5. HWND hwnd; // Owner window.
  6. HANDLE hf; // File handle.
  7.  
  8. // blah, blah, more funtions...
  9. inline void OpenWindow()
  10. {
  11. ZeroMemory(&ofn, sizeof(ofn));
  12. ofn.lStructSize = sizeof(ofn);
  13. ofn.hwndOwner = hwnd;
  14. ofn.lpstrFile = szFile;
  15.  
  16. ofn.lpstrFile[0] = '\0';
  17. ofn.nMaxFile = sizeof(szFile);
  18. ofn.lpstrFilter = "Playlists: m3u.\0*.m3u\0Music Files :mp1, mp2, mp3, wav, ogg.\0*.mp1;*.mp2;*.mp3;*.wav;*.ogg\0";
  19. ofn.nFilterIndex = 1;
  20. ofn.lpstrFileTitle = NULL;
  21. ofn.nMaxFileTitle = 0;
  22. ofn.lpstrInitialDir = NULL;
  23. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
  24.  
  25. // Display the Open dialog box.
  26. if (GetOpenFileName(&ofn)==TRUE)
  27. hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, (LPSECURITY_ATTRIBUTES) NULL,
  28. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
  29. return;
  30. }

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:
C++ Syntax (Toggle Plain Text)
  1.  
  2. for( unsigned int i=0; i < strlen(szFile); i++ )
  3. if (szFile[i] == 92) szFile[i] = 47; // Replace '\' with '/'.

than i call this function:

C++ Syntax (Toggle Plain Text)
  1.  
  2. inline void m3u_to_PlayList()
  3. {
  4. fstream F; F.open(szFile, ios::in);
  5. F.clear(); F.seekp(0, ios::beg);
  6. char Line[260]="0";
  7.  
  8. while( F.get(Line, 260) ) // Load m3u data into the Playlist.
  9. { /* This loop should do something similar to printing the lines
  10.   from the m3u file. I used a message box as an example. */
  11. MessageBox(NULL, Line, "msg", MB_OK);
  12. F.get();
  13. }
  14.  
  15. F.close();
  16. MessageBox(NULL, "Loop done.", "msg", MB_OK);
  17.  
  18. return;
  19. }

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...
Last edited by Prahaai; Mar 13th, 2007 at 6:36 pm. Reason: some typos :p
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
Prahaai is offline Offline
59 posts
since May 2005
Jan 18th, 2008
0

Re: Big Problem

Hi,

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

regards

Click to Expand / Collapse  Quote originally posted by Prahaai ...
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...
Reputation Points: 10
Solved Threads: 0
Newbie Poster
talesfc is offline Offline
1 posts
since Jan 2008
Jan 18th, 2008
0

Re: Open Files with GetOpenFileName

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++.
c++ Syntax (Toggle Plain Text)
  1. #include <windows.h>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. using namespace std;
  6.  
  7. // ... blah, blah, more global variables...
  8. OPENFILENAME ofn; // Common dialog box structure.
  9. char szFile[260]; // Buffer for selected file name.
  10. HWND hwnd; // Owner window.
  11. HANDLE hf; // File handle.
  12.  
  13. // blah, blah, more funtions...
  14. inline void OpenWindow()
  15. {
  16. ZeroMemory(&ofn, sizeof(ofn));
  17. ofn.lStructSize = sizeof(ofn);
  18. ofn.hwndOwner = hwnd;
  19. ofn.lpstrFile = szFile;
  20. ofn.nMaxFile = sizeof(szFile);
  21. ofn.lpstrFilter = "Playlists: m3u.\0*.m3u\0Music Files :mp1, mp2, mp3, wav, ogg.\0*.mp1;*.mp2;*.mp3;*.wav;*.ogg\0";
  22. ofn.nFilterIndex = 2;
  23. ofn.lpstrFileTitle = NULL;
  24. ofn.nMaxFileTitle = 0;
  25. ofn.lpstrInitialDir = NULL;
  26. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
  27.  
  28. // Display the Open dialog box.
  29. GetOpenFileName(&ofn);
  30. // hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, (LPSECURITY_ATTRIBUTES) NULL,
  31. // OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL);
  32. return;
  33. }
  34.  
  35.  
  36. inline void m3u_to_PlayList()
  37. {
  38. ifstream F;
  39. char Line[260] = {0};
  40. F.open(szFile, ios::binary);
  41. if( F.is_open())
  42. {
  43. while( F.read(Line, sizeof(Line)) ) // Load m3u data into the Playlist.
  44. { /* This loop should do something similar to printing the lines
  45.   from the m3u file. I used a message box as an example. */
  46.  
  47.  
  48. sz = F.gcount(); // get number of characters read
  49. cout.write(Line,sz); // write data to the screen
  50. }
  51. F.close();
  52. }
  53.  
  54. cout << "\n\nLoop done\n";
  55. return;
  56. }
  57.  
  58. int main()
  59. {
  60. OpenWindow();
  61. m3u_to_PlayList();
  62. return 0;
  63. }
Last edited by Ancient Dragon; Jan 18th, 2008 at 11:43 pm.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2283
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,961 posts
since Aug 2005
Apr 30th, 2009
0

Re: Open Files with GetOpenFileName

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

C++ Syntax (Toggle Plain Text)
  1. //Call Browse Folder Window, Search Entire Folder and all sub-folders for desired file(s).
  2. //This function was written by Jered McFerron ( JHawkZZ ). It's a pretty handy thing to add to your
  3. //windows application, and I decided to publish this because I've seen many requests and few replies.
  4.  
  5.  
  6. //Some parts of the Browse Folder dialog code taken from http://www.mvps.org/vcfaq/sdk/20.htm.
  7.  
  8.  
  9. #include <windows.h>
  10. #include <shlobj.h>
  11. #include <string.h>
  12.  
  13. //BROWSE FOLDER - Opens a browse folder dialog.
  14. void BrowseFolder( void )
  15. {
  16. TCHAR path[MAX_PATH];
  17. BROWSEINFO bi = { 0 };
  18. bi.lpszTitle = ("All Folders Automatically Recursed.");
  19. LPITEMIDLIST pidl = SHBrowseForFolder ( &bi );
  20.  
  21. if ( pidl != 0 )
  22. {
  23. // get the name of the folder and put it in path
  24. SHGetPathFromIDList ( pidl, path );
  25.  
  26. //Set the current directory to path
  27. SetCurrentDirectory ( path );
  28.  
  29. //Begin the search
  30. SearchFolder( path );
  31.  
  32.  
  33. // free memory used
  34. IMalloc * imalloc = 0;
  35. if ( SUCCEEDED( SHGetMalloc ( &imalloc )) )
  36. {
  37. imalloc->Free ( pidl );
  38. imalloc->Release ( );
  39. }
  40. }
  41. }//BROWSE FOLDER
  42.  
  43.  
  44. //SEARCH FOLDER - Searches folder and all sub-folders for audio files.
  45. void SearchFolder( TCHAR * path )
  46. {
  47. //Declare all needed handles
  48. WIN32_FIND_DATA FindFileData;
  49. HANDLE hFind;
  50.  
  51. TCHAR filename[ MAX_PATH + 256 ];
  52. TCHAR pathbak[ MAX_PATH ];
  53.  
  54. //Make a backup of the directory the user chose
  55. strcpy( pathbak, path );
  56.  
  57. //Find the first file in the directory the user chose
  58. hFind = FindFirstFile ( "*.*", &FindFileData );
  59.  
  60. //Use a do/while so we process whatever FindFirstFile returned
  61. do
  62. {
  63. //Is it valid?
  64. if ( hFind != INVALID_HANDLE_VALUE )
  65. {
  66. //Is it a . or .. directory? If it is, skip, or we'll go forever.
  67. if ( ! ( strcmp( FindFileData.cFileName, "." ) ) || ! ( strcmp( FindFileData.cFileName, ".." ) ) )
  68. {
  69. continue;
  70. }
  71.  
  72. //Restore the original directory chosen by the user
  73. strcpy( path, pathbak );
  74.  
  75. //Append the file found on to the path of the directory the user chose
  76. sprintf( path, "%s\\%s", path, FindFileData.cFileName );
  77.  
  78. //If SetCurrentDirectory Succeeds ( returns 1 ) the current file is a directory. Pause this function,
  79. //and have it call itself. This will begin the whole process over in a sub directory.
  80. if ( ( SetCurrentDirectory( path ) ) )
  81. {
  82. SearchFolder( path );
  83. }
  84.  
  85. //Otherwise right here is where you need to insert what you want to do.
  86. //As an example let's add the filename to a list box.
  87. //INSERT WHAT YOU WANT DONE BELOW!
  88. SendMessage( m_listbox_hwnd, LB_ADDSTRING, 0, path ); //<--INSERT WHAT YOU WANT DONE HERE!
  89. //m_listbox_hwnd is just an example handle to a fake listbox. Delete all this
  90. and put your own code.
  91.  
  92. }
  93. }
  94. while ( FindNextFile ( hFind, &FindFileData ) && hFind != INVALID_HANDLE_VALUE );
  95.  
  96. FindClose ( hFind );
  97. }//SEARCH FOLDER

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

Please help.
Last edited by Alexander22; Apr 30th, 2009 at 3:26 pm.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Alexander22 is offline Offline
1 posts
since Apr 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: How does this code work?
Next Thread in C++ Forum Timeline: Dynamic array, with struct, and pointers....help....





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC