簡體   English   中英

獲取文件的絕對路徑

[英]Getting absolute path of a file

如何在 Unix 上的 C 中將相對路徑轉換為絕對路徑? 有沒有方便的系統功能呢?

在 Windows 上有一個GetFullPathName函數可以完成這項工作,但我在 Unix 上沒有找到類似的東西......

使用realpath()

realpath()函數應從file_name指向的路徑名派生出一個絕對路徑名,它命名同一個文件,其解析不涉及 ' . '、' .. ' 或符號鏈接。 生成的路徑名應存儲為以空字符結尾的字符串,最多為{PATH_MAX}字節,在resolved_name指向的緩沖區中。

如果resolved_name是空指針,則realpath()的行為是實現定義的。


以下示例為由 symlinkpath 參數標識的文件生成絕對路徑名。 生成的路徑名存儲在實際路徑數組中。

#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);
}

還有一個小路徑庫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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM