ファイルの絶対パスを取得する
-
04-07-2019 - |
質問
UnixのCで相対パスを絶対パスに変換するにはどうすればよいですか? これに便利なシステム機能はありますか?
Windowsには、ジョブを実行する GetFullPathName
関数がありますが、Unixで類似したものは見つかりませんでした...
解決
realpath()を使用します。
realpath()
関数は派生し、 が指すパス名からfile_name
、絶対パス名 同じファイルに名前を付け、その解像度 「。
」、「..
」、または シンボリックリンク。生成されたパス名 ヌル終了として保存されます 文字列、最大{PATH_MAX}
まで が指すバッファ内のバイト数resolved_name
。
resolved_name
がヌルポインターの場合、realpath()
の動作は 実装定義。
次の例では、 ファイルの絶対パス名 symlinkpathによって識別されます 引数。生成されたパス名は actualpath配列に格納されます。
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;
ptr = realpath(symlinkpath, actualpath);
他のヒント
stdlib.h
realpath()
を試してください
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);
}
&quot; getcwd&quot;も試してください
#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.
クロスプラットフォームで機能する小さなパスライブラリ 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
所属していません StackOverflow