programing

파일의 절대 경로 가져오기

javaba 2022. 9. 30. 10:47
반응형

파일의 절대 경로 가져오기

Unix에서 상대 경로를 C의 절대 경로로 변환하려면 어떻게 해야 합니까?편리한 시스템 기능이 있나요?

Windows 에는,GetFullPathName기능을 하는데 UNIX에서는 비슷한 것을 찾을 수 없었습니다.

realpath()를 사용합니다.

realpath()함수는 다음에 의해 지적된 경로 이름에서 파생되어야 한다.file_name, 같은 파일에 이름을 붙이는 절대 패스명.해상도에는 「」이 포함되지 않습니다..', '..' 또는 심볼릭 링크.생성된 경로명은 null 종단 문자열로 저장되어야 하며, 최대값은 다음과 같습니다.{PATH_MAX}바이트, 에 의해 지정된 버퍼 내의resolved_name.

한다면resolved_namenull 포인터입니다.realpath()는 구현 정의되어 있습니다.


다음 예제에서는 symlinkpath 인수로 식별된 파일의 절대 경로 이름을 생성합니다.생성된 경로 이름은 실제 경로 배열에 저장됩니다.

#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;


ptr = realpath(symlinkpath, actualpath);

해라realpath()에서stdlib.h

char filename[] = "../../../../data/000000.jpg";
char* path = realpath(filename, NULL);
if(path == NULL){
    printf("cannot find file with name[%s]\n", filename);
} else{
    printf("path[%s]\n", path);
    free(path);
}

크로스 플랫폼에서도 동작하는 작은 패스 라이브러리 cwalk도 있습니다.그러기 위한 cwk_path_get_absolute가 있습니다.

#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  char buffer[FILENAME_MAX];

  cwk_path_get_absolute("/hello/there", "./world", buffer, sizeof(buffer));
  printf("The absolute path is: %s", buffer);

  return EXIT_SUCCESS;
}

출력:

The absolute path is: /hello/there/world

"getcwd"도 시도해 보십시오.

#include <unistd.h>

char cwd[100000];
getcwd(cwd, sizeof(cwd));
std::cout << "Absolute path: "<< cwd << "/" << __FILE__ << std::endl;

결과:

Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp

테스트 환경:

setivolkylany@localhost$/ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.6 (jessie)
Release:    8.6
Codename:   jessie
setivolkylany@localhost$/ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
setivolkylany@localhost$/ g++ --version
g++ (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

언급URL : https://stackoverflow.com/questions/229012/getting-absolute-path-of-a-file

반응형