디렉토리 및 파일 선택하기 - GetOpenFileName, CFileDialog, SHBrowseForFolder (2024)

관련글 :

MFC CFileDialog - 파일선택 다이얼로그

디렉토리 및 파일 선택하기 - GetOpenFileName, CFileDialog, SHBrowseForFolder

SHELL 프로그램 - 디렉토리의 위치를 얻기위한 프로그램

파일 선택하기

파일을 선택하기 위한 방법은 이미 존재하는 함수를 사용하면 된다. 디렉토리 선택 역시 쉘 함수를 사용하면 된다. 파일을 다루려면 폴더의 선택과 파일의 선택이 우선 필요한 경우가 있다. 파일 선택을 위한 방법 이다.

파일 선택하기

MFC을 사용한 경우와 SDK을 사용한 경우를 생각할 수 있다. 프로젝트를 만들 때 MFC을 사용하지 않도록 설정하면 CFileDialog 클래스를 사용할 수 없다. 이것을 default로 MFC에서 제공하는 클래스를 붙일 수 없도록 설정이 되어 있기 때문이다. 물론 프로젝트의 설정을 바구면 MFC을 사용할 수는 있다.

어째든 그냥 SDK에서 파일 선택 관리 다이얼로그를 호출하려면

GetOpenFileName() 함수를

사용하면 된다.

폴더선택하기

폴더 선택을 위한 디렉토리를 표시하는 클래스를 작성할 수도 있지만, 이미 있는 것을 사용하면 편리하다. 익숙한 것도 있다. 디렉토리를 선택하기 위한 함수는

SHBrowseForFolder()

사용하면 된다. 함수명 앞에 SH로 시작하는 것은 Shell Program 라이브러리 이다.

프로그램 예

FileAccsView.h

class CFileAccsView : public CView
{
protected: // create from serialization only
CFileAccsView();
DECLARE_DYNCREATE(CFileAccsView)

// Attributes
public:
CFileAccsDoc* GetDocument();

// 클래스에서 사용할 변수를 잡고
char m_dirName[MAX_PATH]; // 선택된 디렉토릴 저장 예:test
char m_dirFolderPath[MAX_PATH]; // 선택된 디렉토리의 path명 까지 포함한 디렉토리예: C:\tmp\test


char m_filename[MAX_PATH]; // 파일명을 저장 한다.

char m_filenamePath[MAX_PATH]; //Path까지를 포함한 파일명을저장 한다

char *m_MultFileList[100]; // 파일 리스트를 저장할 포인터 공간
int m_fCount; // 파일명의 갯수

char m_buff[1024]; // 임시버퍼

...

};

FileAccsView.cpp

/////////////////////////////////////////////////////////////////

//클래스 생성자

// 각 변수의 초기화
//

CFileAccsView::CFileAccsView()
{
// TODO: add construction code here

m_dirName[0] = 0;;
m_filename[0] = 0;;
m_filenamePath[0]= 0;

strcpy(m_dirFolderPath, "C:\\");

m_fCount = 0;
memset(&m_MultFileList,0,sizeof(m_MultFileList));
}

/////////////////////////////////////////////////////////////////

//클래스 소멸자

// 파일명의 리스트를 삭제 한다. 동적할당 이므로 메모리를 반납 한다.

//

CFileAccsView::~CFileAccsView()
{
for (int cnt = 0;cnt < m_fCount;cnt++) {
if (m_MultFileList[cnt])
delete m_MultFileList[cnt];
m_MultFileList[cnt] = NULL;
}
}

/////////////////////////////////////////////////////////////////

// 파일을 선택하기 위한 SDK 함수GetOpenFileName()을 사용한 예
//

void CFileAccsView::OnGetFileName()
{
// TODO: Add your command handler code here

OPENFILENAME Ofn;

strcpy(m_filename, "*.*");

memset(&Ofn,0,sizeof(OPENFILENAME));
Ofn.lStructSize = sizeof(OPENFILENAME);
Ofn.hwndOwner = this->m_hWnd;
Ofn.lpstrFilter = "모든파일(*.*)\0*.*\0Text Files(*.txt)\0*.*\0";
Ofn.lpstrFile = m_filename;
Ofn.nMaxFile = MAX_PATH-4;
Ofn.Flags = OFN_EXPLORER | OFN_ALLOWMULTISELECT;
Ofn.lpstrInitialDir = m_dirFolderPath; // "C:\\";

if (GetOpenFileName(&Ofn)) {
sprintf(m_buff, "File : %s", m_filename);
AfxMessageBox(m_buff);
} else{
AfxMessageBox("파일을 다시 선택하세요",MB_OK);
}
}

/////////////////////////////////////////////////////////////////

// 파일을 선택하기 위한 MFC함수CFileDialog ()을 사용한 예
//

void CFileAccsView::OnCfdmfc()
{
// TODO: Add your command handler code here

strcpy(m_filename, "*.*"); // 다이얼로그의 선택 편집창의 초기 표시 설정 - 모든 파일이 보이도록 와일드 카드

static char szFilter[] = "All Files(*.*) | *.* ||"; // 아래 파일 타입을 설정 한다.
CFileDialog dlg (TRUE, NULL, NULL,
OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT
, szFilter, NULL);

dlg.m_ofn.lpstrFile = m_filename; // 선택된 파일명을 저장할 변수 설정
dlg.m_ofn.nMaxFile = MAX_PATH; // 파일명의 최대 크기 위의 버퍼를 넘지 않도록 한다. m_ofn.lpstrFile변수에 저장할 최대크기

if (dlg.DoModal() == IDOK) { // 모달 다이얼로그를 실행하고 OK 버튼을 누르면

CString str = dlg.GetFileName(); // 이미 m_filename변수에 저장되어 필요는 없다. 단지 CString에 저장.
//strcpy(m_filename, str.GetBuffer(MAX_PATH) );

CString strpath = dlg.GetPathName(); //파일의 풀 디렉토리 명을 얻는다.
strcpy(m_filenamePath, strpath.GetBuffer(MAX_PATH) );

Invalidate();
} else {
m_filename[0] = 0;
m_filenamePath[0] = 0;
}

}

#if 0 // 2008
CFileDialog dlgFile(TRUE);
CString fileName;

const int c_cMaxFiles = 100;
const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;

dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);

dlgFile.GetOFN().nMaxFile = c_cMaxFiles;

dlgFile.DoModal();

fileName.ReleaseBuffer();

#endif

/////////////////////////////////////////////////////////////////

// 파일을 선택할 때여러개의 파일을 선택하기 위한CFileDialog ()을 사용한 예
//

void CFileAccsView::OnMulfile()
{
// TODO: Add your command handler code here

strcpy(m_buff, "*.*");

static char szFilter[] = "All Files(*.*) | *.* ||";


CFileDialog dlg (TRUE, NULL, NULL,

OFN_ALLOWMULTISELECT, // 이것이 멀티 파일을 선택할 수있는 옵션이다.

szFilter, NULL);

dlg.m_ofn.lpstrFile = m_buff;
dlg.m_ofn.nMaxFile = MAX_PATH;

if (dlg.DoModal() == IDOK) {

// 기존의 파일 리스트를 제거 한다.

for (int cnt = 0;cnt < m_fCount;cnt++) {

if (m_MultFileList[cnt])
delete m_MultFileList[cnt];
m_MultFileList[cnt] = NULL;
}

m_fCount = 0;

// 선택된 파일 리스트를 얻는다.

POSITION pos = dlg.GetStartPosition ();

while (pos)
{
CString str = dlg.GetNextPathName (pos);

m_MultFileList[m_fCount] = new char[str.GetLength()+4]; // 파일명을 저장한 공간 확보
strcpy(m_MultFileList[m_fCount], str.GetBuffer(MAX_PATH) ); // 파일명 복사

TRACE("File : %s\n", m_MultFileList[m_fCount] );
m_fCount++;
}

Invalidate(); // WM_PAINT을 호출하면 윈도우 화면 갱신
}

}

/////////////////////////////////////////////////////////////////

// 디렉토리를 선택하기 위한 shell 사용한 예
//

void CFileAccsView::OnGetFDir()
{
// TODO: Add your command handler code here

BROWSEINFO bi;
LPITEMIDLIST idl;

ZeroMemory(&bi,sizeof(BROWSEINFO));

bi.hwndOwner = this->m_hWnd;
bi.pszDisplayName = m_dirName; // 선택된 디렉토리명 저장
bi.lpszTitle = "폴더를 선택해 주세요";
bi.ulFlags = BIF_EDITBOX //선택된디렉토리명을 표시하고 편집할 수 있는 창
| 0x0040 //새로운 디렉토리를 만들수 있는 버튼 추가
;

idl = SHBrowseForFolder(&bi);

if (idl) {
SHGetPathFromIDList(idl, m_dirFolderPath); // 전체 PATH을 포함한 디렉토리명

AfxMessageBox(m_dirFolderPath);
}
}

--------------------------------------------------------------------

http://wodev.tistory.com/entry/CFileDialog-에서-내컴퓨터를-초기-폴더로-지정하기

CString sf_GetComputerDir()
{
IMalloc *pShellMalloc = NULL;
IShellFolder *psfParent;
LPITEMIDLIST pidlItem = NULL;
LPITEMIDLIST pidlRelative = NULL;
STRRET str;
WCHAR szDisplayName[MAX_PATH] = L"";
WCHAR szPath[MAX_PATH] = L"";

HRESULT hres = SHGetMalloc(&pShellMalloc);
if (FAILED(hres))
return _T("");

hres = SHGetSpecialFolderLocation(NULL, CSIDL_DRIVES, &pidlItem);
if (SUCCEEDED(hres))
{
hres = SHBindToParent(pidlItem, IID_IShellFolder, (void**)&psfParent, (LPCITEMIDLIST*)&pidlRelative);
if (SUCCEEDED(hres))
{
memset(&str, 0, sizeof(str));
hres = psfParent->GetDisplayNameOf(pidlRelative, SHGDN_NORMAL, &str);
if (SUCCEEDED(hres))
StrRetToBuf(&str, pidlItem, szDisplayName, ARRAYSIZE(szDisplayName));

memset(&str, 0, sizeof(str));
hres = psfParent->GetDisplayNameOf(pidlRelative, SHGDN_NORMAL | SHGDN_FORPARSING, &str);
if (SUCCEEDED(hres))
StrRetToBuf(&str, pidlItem, szPath, ARRAYSIZE(szPath));

psfParent->Release();
}
}

if (pidlItem)
pShellMalloc->Free(pidlItem);
pShellMalloc->Release();

return szPath;
}

CFileDialog dlg(FALSE, _T("rtf"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
_T("*.*|*.*||"));

dlg.m_ofn.lpstrInitialDir = sf_GetComputerDir();
if(dlg.DoModal() == IDOK)
{
m_sPath = dlg.GetPathName();
}

디렉토리 및 파일 선택하기 - GetOpenFileName, CFileDialog, SHBrowseForFolder (2024)
Top Articles
Exclusive: Leaked Footage Of Mikayla Campinos
Find Out: Is Mikayla Campinos Deceased?
Myexperience Login Northwell
Apex Rank Leaderboard
Undergraduate Programs | Webster Vienna
A Complete Guide To Major Scales
Katie Boyle Dancer Biography
Chastity Brainwash
World History Kazwire
Programmieren (kinder)leicht gemacht – mit Scratch! - fobizz
Wordle auf Deutsch - Wordle mit Deutschen Wörtern Spielen
Ivegore Machete Mutolation
Hoe kom ik bij mijn medische gegevens van de huisarts? - HKN Huisartsen
Willam Belli's Husband
Ms Rabbit 305
Indiana Wesleyan Transcripts
Why do rebates take so long to process?
Football - 2024/2025 Women’s Super League: Preview, schedule and how to watch
Xfinity Outage Map Fredericksburg Va
Greenville Sc Greyhound
Living Shard Calamity
Bill Remini Obituary
eugene bicycles - craigslist
Pawn Shop Moline Il
Meta Carevr
SOGo Groupware - Rechenzentrum Universität Osnabrück
What Is a Yurt Tent?
Stickley Furniture
Current Students - Pace University Online
Federal Express Drop Off Center Near Me
Craigslist Sf Garage Sales
Cavanaugh Photography Coupon Code
L'alternativa - co*cktail Bar On The Pier
Chicago Pd Rotten Tomatoes
Frommer's Belgium, Holland and Luxembourg (Frommer's Complete Guides) - PDF Free Download
Log in or sign up to view
Marie Peppers Chronic Care Management
Gold Nugget at the Golden Nugget
Soulstone Survivors Igg
Wattengel Funeral Home Meadow Drive
Mohave County Jobs Craigslist
The Best Restaurants in Dublin - The MICHELIN Guide
craigslist | michigan
ESA Science & Technology - The remarkable Red Rectangle: A stairway to heaven? [heic0408]
Subdomain Finder
Shell Gas Stations Prices
Woody Folsom Overflow Inventory
Europa Universalis 4: Army Composition Guide
Kjccc Sports
Menu Forest Lake – The Grillium Restaurant
Zits Comic Arcamax
Códigos SWIFT/BIC para bancos de USA
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5689

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.