[질문 내용]
인터넷으로 읽어들이는 파일의 이름은
abc[1].gif
이런 형식으로 뒤에 []<- 이 표시가 붙습니다.
제가 아이콘을 저장하려는데 모두 이표시가 붙어 프로그램으로 이걸 다 지우려고 합니다.
대충의 알고리즘은
1. 프로그램이 속한 폴더의 파일을 모두 읽어들입니다.
2. 파일의 이름에서 '['로 시작 ']'로 끝나는 부분을 삭제합니다.
- 이름바꾸기, 특정 문자열 입력 등의 기능도 짜볼 생각입니다.
ㅡ"ㅡ;;; 간단하네요...
그래도 억쑤로 유용할꺼 같습니다..
가끔씩 문서, 아이콘, mp3 파일등 많은 자료의 이름을 바꿀 경우가 생길때가 있으니깐요..
하지만 문젠.. 지가 C언어 초보라는 겁니다...
그래서 1번 알고리즘에 대해 몰라서 이렇게 질문합니다.
어떤 폴더에서 파일을 검색하는 방법과 모든 파일을 읽는 방법을 알고 싶네요..
[답변 내용]
MSDN 의 예제를 약간 수정해봤습니다.
아래 예제는 현재 폴더의 파일들의 속성과 파일이름을 나열하는 함수죠.
파일 이름을 검색해서 [ 과 ] 을 포함한 그 사이의 스트링을 삭제한 후 파일 이름을 바꾸면 될 것 같습니다.
파일 이름 바꾸는건 rename() 함수란게 있더군요.
제가 짜볼려고 했는데 그래도 님이 먼저 해보시는게 좋을거 같아서 힌트만 드립니다 ^^ 막히면 쪽지 주세요......
#include < stdio.h >
#include < io.h >
#include < time.h >
void main( void )
{
struct _finddata_t c_file;
long hFile;
/* Find first .c file in current directory */
if( (hFile = _findfirst( "*.*", &c_file )) == -1L )
printf( "No files in current directory!\n" );
else
{
printf( "Listing of files\n\n" );
printf( "\nRDO HID SYS ARC dir FILE DATE %25c SIZE\n", ' ' );
printf( "--- --- --- --- --- ---- ---- %25c ----\n", ' ' );
/* Find the rest of the .c files */
do
{
printf( ( c_file.attrib & _A_RDONLY ) ? " Y " : " N " );
printf( ( c_file.attrib & _A_SYSTEM ) ? " Y " : " N " );
printf( ( c_file.attrib & _A_HIDDEN ) ? " Y " : " N " );
printf( ( c_file.attrib & _A_ARCH ) ? " Y " : " N " );
printf( ( c_file.attrib & _A_SUBDIR ) ? " Y " : " N " );
printf( " %-12s %.24s %9ld\n",
c_file.name, ctime( &( c_file.time_write ) ), c_file.size );
}while( _findnext( hFile, &c_file ) == 0 );
_findclose( hFile );
}
}
참고:
rename 함수의 원형입니다. stdio.h 나 io.h 헤더가 필요하죠.
int rename( const char *oldname, const char *newname );
그리고, _A_SUBDIR 속성의 경우 폴더(디렉토리)인데, 재귀함수 방식을 이용해서 하위폴더까지 모두 처리할 수도 있죠.
[_findfirst 예제]
#include <stdio.h>
#include <io.h>
void main( void )
{
char imsi[500][500];
int i=0;
struct _finddata_t c_files;
long hFile;
if ( (hFile = _findfirst( "*.*", &c_files )) == -1L )
{
printf( "디렉토리가 없습니다.\n" ); //-1이면 없음다
}
else//0이니깐 ㄱㄱ
{
while ( _findnext( hFile, &c_files ) == 0 )
{
if ( c_files.size == 0 && !(fopen(c_files.name, "rb")) )
printf( "%s\n", c_files.name );
sprintf(imsi[i],"%s",c_files.name );
i++;
}
_findclose( hFile );
}
}
[파일명 읽기 ... findfirst / _findfirst ]
VC 에서는 _findfirst(), _findnext(), _findclose()를 사용한다.
#include <stdio.h>
#include <io.h>
main()
{
struct _finddata_t stFileInfo;
long hFile;
char cpFileSpec[256];
sprintf(cpFileSpec, "C:\\TEMP\\*.dat\0");
if ( (hFile = _findfirst( cpFileSpec, &stFileInfo)) == -1 )
{
printf( "file not found.\n" );
}
else
{
printf( "%s\n", stFileInfo.name );
while ( _findnext( hFile, &stFileInfo) == 0 )
{
printf( "%s\n", stFileInfo.name );
}
_findclose( hFile );
}
}
[VC 에서의 예제]
Visual C++ 에서만 동작합니다.
다른 컴파일러에서는 잘 모르겠습니다.
#include "iostream"
#include "string"
#include "io.h"
using namespace std;
int main()
{
char files[256][256]; // 파일명최대255자, 파일갯수최대256개
int nFiles = 0;
struct _finddata_t c_file;
intptr_t hFile;
// *.* 에적당한폴더명을넣으면됩니다.
// 예를들면"aaa\*.*"
if( (hFile = _findfirst( "*.*", &c_file )) == -1L )
cout << "No file(s) in that directory!" << endl;
else
{
// 문자열복사
do
{
strcpy(files[nFiles], c_file.name);
++nFiles;
} while( _findnext( hFile, &c_file ) == 0 );
_findclose(hFile);
}
for ( int i = 0; i < nFiles; i++ )
{
cout << files[i] << endl;
}
cout << endl;
cout << "Total " << nFiles << " files." << endl;
return 0;
}
[C++ 에서의 예제]
#include <stdio.h>
#include <windows.h>
//---- 이부분만 수정하시면 됩니다 주의하실점은 폴더간에 표시를 \\<-- 두번해야 한다는것
// txt파일만을 찾고 싶으시다면은 *.txt로 바꾸시면 되겟지요?
#define PATH "C:\\Windows\\*.*"
void main()
{
HANDLE hSrch; // 핸들
TCHAR Path[MAX_PATH] = PATH; // 파일을 찾을 경로입니다.
WIN32_FIND_DATA data; // 파일의 정보
BOOL bResult = TRUE;
char buf[MAX_PATH][MAX_PATH];
int count =0 ;
// 검색을 시작하는 역활을 합니다.
hSrch = FindFirstFile( Path , &data ) ;
if( hSrch == INVALID_HANDLE_VALUE ) return ;
// 반복문을 돕니다.
while( bResult )
{
if( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// 폴더와 하위 디렉토리까지 출력
printf( "[ %s ] " , data.cFileName);
}
else
{
// 파일명 출력 ( 님이 필요하신부분은 이거일껍니다 )
// 이부분에서 배열에 저장을 하시면 되지요..
strcpy( buf[count++] , data.cFileName ) ;
// printf( "%s \n" , data.cFileName) ;
}
// 다음 파일을 찾는것
bResult = FindNextFile( hSrch , &data ) ;
}
// 검색을 종료 합니다
FindClose( hSrch ) ;
// 배열에 저장한것을 출력해준다
for( int i=0 ; i<count ; i++)
{
printf("%s \n" , buf[i] ) ;
}
}