VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-to-compare-paths-of-two-files/

⇱ C++ Program to Compare Paths of Two Files - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program to Compare Paths of Two Files

Last Updated : 15 Dec, 2022

As we are given two paths of two files, we have to compare these two paths and check whether they are equal or greater or smaller using a C++ program.

Input:

path1 = "/a/b/c" , path2 = "/a/b/"

Output:

path1 is greater than path2

Approaches:

Using built-in compare function :

  1. To store paths use string as data type 
  2. Use pathname1. Compare( pathname2 ), to compare two paths , this will return three values  greater that 0 , less than 0 or equal to 0 

Example:


Output
/a/b/c is greater than /a/b/
/a/b is equal to /a/b
/a/b is less than /a/b.

Using iteration(for & while loop) :

  1. To store paths use string as data type
  2. Use for or while loop and compare each character of them one by one.

Syntax:

while(path1[i] != '\0' || path2[i] != '\0'){
 //compare the character
 //increment value of i
}

OR

for(int i = 0; path1[i] != '\0' || path2[i] != '\0'; i++){
 //compare the character
}

Below is the implementation of the above approach:


Output
/a/b/c is not equal to /a/b/
/a/b is equal to /a/b
/a/b is not equal to /a/b.

Using Comparison operators:

  1. To store paths use string as data type
  2. Use comparison operators (<, >, ==) to compare two paths.

syntax:

if(path1 > path2)
 // path1 is greater
else if(path1 < path2)
 // path2 is greater
else
 // both paths are same

Example:


Output
/a/b/c is greater than /a/b/
/a/b is equal to /a/b
/a/b is less than /a/b.

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags: