سؤال

وكيف يمكنني تحويل مسار نسبي إلى مسار مطلق في C على يونكس؟ هل هناك وظيفة الجهاز مريحة لهذا؟

في ويندوز هو هناك وظيفة GetFullPathName التي لا وظيفة، ولكن لم أجد شيئا من هذا القبيل على يونيكس ...

هل كانت مفيدة؟

المحلول

استخدم 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);

نصائح أخرى

وحاول 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);
}

وأيضا محاولة "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.

وهناك أيضا مكتبة صغيرة مسار 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top