Coding & Programming/C, C++

[C/C++] 전체 경로에서 파일명 추출하기(extract only the file name from the entire path : strrc

mainCodes 2021. 2. 28. 08:44

[C/C++] 전체 경로에서 파일명 추출하기(extract only the file name from the entire path : strrchr, strcpy functions example)

 

안녕하세요 JollyTree 입니다.

코딩하다가 전체경로 문자열에서 파일명을 추출할 필요가 있을 때가 있습니다. 여러 방법 중 오늘은 strchr, strcpy 함수를 이용하여 아래와 같이 전체 경로에서 파일명만을 추출하는 방법을 포스팅합니다.

 

- 전체 경로 "c:\\test\\tistory.com\\codes.txt" 에서 "codes.txt"만 추출

 

예제(Example)

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
#pragma warning(disable: 4996)
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <string.h>
 
#ifdef _GET_CURRENT_FILENAME
#include <Windows.h>
#endif
 
int main()
{
    char path[256= "c:\\test\\tistory.com\\codes.txt";
    char filename[256= "";
    char* ptr = NULL;
 
#ifdef _GET_CURRENT_FILENAME
    ::GetModuleFileName(NULL, path, 256); //컴파일된 실행파일의 경로를 구하여 예제에 활용
#endif
 
    printf("[입력한 경로]=%s\n", path);
    ptr = strrchr(path, '\\');     //문자열(path)의 뒤에서부터 '\'의 위치를 검색하여 반환
 
    if (ptr == NULL)
        strcpy(filename, path);
    else
        strcpy(filename, ptr + 1); // 포인터에 +1을 더하여 파일이름만 추출
 
    printf("\n[실행결과]=%s\n", filename);
 
    return 0;
}
 

실행결과