How to Implement the realpath() Function in C++

Jay Shaw Feb 02, 2024
  1. Implement the realpath() Function in C++
  2. Find the Absolute Path Using the realpath() Function in C++
  3. Use One Line Command to Find the Absolute Path Using the realpath() Function in C++
  4. Conclusion
How to Implement the realpath() Function in C++

The function realpath() was first documented in POSIX 1997 and POSIX 2008 as a function to find the absolute path of a file inside a directory.

This article explains the implementation of the function realpath() in C++. It can be implemented into the system to find the absolute path of a file using C++.

Implement the realpath() Function in C++

The main use of the realpath() in C++ is to find the pathname of a file when all its symbolic links are resolved.

Before we discuss the implementation of realpath() in C++, here are some basic concepts that need to be known:

  • Symbolic Link: A symbolic link points to its target file, but it is different than a shortcut, as the computer treats the symbolic link as a file on its own instead of a link to the target file. It acts as a type of file that, when accessed, takes the user to the location where the original file exists, and any changes made to the symbolic link also reflect in the original file.
  • Absolute Path: When the path to a file is written up to its root directory, like \usr\bin\main, it is known as its absolute path.
  • Relative Path: If the current working directory is set as usr\bin, then the file whose absolute path is /usr/bin/main can be referenced simply as main. For example, the UNIX command: cp /usr/bin/main /usr/bin/main.bak and the command: cp mailbox mailbox.bak accomplish the same if the working directory is /usr/ast.

The pathname found by the function realpath() in C++ is not necessarily absolute if the value supplied is a relative name, but that also depends on whether any symbolic link is traversed with absolute names for the link value. If it does, then the output is an absolute name.

Find the Absolute Path Using the realpath() Function in C++

Let’s create a program that finds a file’s absolute path using realpath() in C++. This example is demonstrated in Linux (in windows, the separator is \).

  1. Open the text editor in any Linux distribution with the .cpp extension.

  2. The program has five import files: limits.h to include the PATH_MAX sub-function, stdio for input-output functions, stdlib, string for string functions, cerrno for error cases.

  3. Inside the main function, a variable is created - a char array buffer[] with size set as PATH_MAX. Using PATH_MAX is a better practice for storing pathnames instead of just guessing.

  4. realpath() in C++ takes in two parameters: filename and resolved name. It returns a pointer to the resolved name; otherwise, an error flag is returned.

    char *path = realpath("test.py", buffer);
    
  5. If a resolved name is returned successfully by the function realpath() in C++, the value inside the variable buffer gets printed.

    if (path) {
      printf("Absolute Path = %s.\n", buffer);
    }
    
  6. If the realpath() function returns a null pointer, the program raises an error flag using the errno function.

    char* errStr = strerror(errno);
    

    The errno function is a member function of the cerrno library. It returns a numerical error code, but using the function strerror converts it into its corresponding string value: char* errStr = strerror(errno).

  7. The perror prints an error message to stder. The function first prints the text provided inside braces, followed by the error message.

    perror("realpath");
    
  8. Lastly, the program exits using the EXIT_FAILURE termination code inside the else block.

    exit(EXIT_FAILURE);
    

Code:

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <cerrno>

int main(void) {
  char buffer[PATH_MAX];
  char* path = realpath("test.py", buffer);
  if (path) {  // or: if (path != NULL)
    printf("Absolute Path = %s.\n", buffer);
  } else {
    char* errStr = strerror(errno);
    printf("String Error: %s\n", errStr);

    perror("realpath");
    exit(EXIT_FAILURE);
  }
  return 0;
}

Compilation:

As the code is written in Linux, it must be compiled using the terminal. Save the text file in which the code is written with an appropriate name (ex: C-realpath) and with the .cpp extension.

The file will be compiled using the gcc compiler, and a new application will be created to run the code.

Use the syntax below:

gcc -o realpath2 C-realpath.cpp

The above syntax will successfully compile the code unless there are some errors. Once compiled, the compiler creates an output application - realpath2 for our code.

To run the application, type the syntax:

./realpath2

Output:

jay@jay-virtual-machine:~$ gcc -o realpath2 C-realpath.cpp
jay@jay-virtual-machine:~$ ./realpath2
Absolute Path = /home/jay/test.py.

As the file test.py exists in the system, the program prints its absolute path.

In case an incorrect name is provided for the file, or if the file is missing, the application prints the error code:

jay@jay-virtual-machine:~$ ./realpath2
String Error: No such file or directory
realpath: No such file or directory

Use One Line Command to Find the Absolute Path Using the realpath() Function in C++

The function realpath() in C++ can also be implemented by single-line commands in Linux. This saves the programmer from creating text files to write code and compiling them separately.

To compile the code, write the following syntax inside the terminal:

gcc -o realpath -x c - <<< $'#include<stdlib.h>\n#include<stdio.h>\nint main(int c,char**v){puts(realpath(v[1],0));}'

What the code does:

  1. The gcc -o realpath creates an output application realpath using the gcc compiler.
  2. The code has two library packages: stdlib and stdio.
  3. Inside the main method, two variables are created: an integer variable c and a pointer v.
  4. The puts(realpath(v[1],0)) returns the string literal returned from the realpath() function.

A filename or path needs to be provided to the output application realpath to generate an output. In this example, a folder inside the file system is passed to the application, and it returns the file’s absolute path.

Output:

jay@jay-virtual-machine:~$ ./realpath snap
/home/jay/snap

As there is no error exception inside the code, in case the input is a missing file, it throws errors:

jay@jay-virtual-machine:~$ ./realpath vid
Segmentation fault (core dumped)

Conclusion

This article explains how to implement the function realpath() in C++ to find the absolute path of a file. After going through the article, the reader can derive the absolute path for files using realpath() in C++.