Write a program in C that solves the following problem: The file has a list of file…
- User
Write a program in C that solves the following problem:
The file has a list of file paths of the form /dir1/dir2/file1. Among these paths find the deepest common folder in the hierarchy for all the files. For example for files: /aaa/bbb/ccc/ddd /aaa/bbb/ccc/fff/ggg /aaa/bbb/fff/eee This is /aaa/bbb
Do not use any third-party libraries or frameworks, only standard C libraries. The program must check the correctness of user input. The name of the file used is specified by the user via stdin. Use dynamic arrays, pointers, malloc(), realloc() and free() functions.
- Assistant
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_PATH 1024 char* get_deepest_common_folder(const char** paths, unsigned int num_paths) { char* res = (char*) malloc(MAX_PATH); memset(res, 0, MAX_PATH); if (num_paths == 0) { return res; } char temp[MAX_PATH]; strcpy(temp, paths[0]); char* token = strtok(temp, "/"); while (token != NULL) { int found = 1; for (unsigned int i = 1; i < num_paths; i++) { if (strstr(paths[i], token) != paths[i]) { found = 0; break; } } if (found) { if (strlen(res) > 0) { strcat(res, "/"); } strcat(res, token); } else { break; } token = strtok(NULL, "/"); } return res; } int main() { char file_name[256]; printf("Enter the file name: "); scanf("%s", file_name); FILE* file = fopen(file_name, "r"); if (!file) { printf("File not found.\n"); return 1; } size_t capacity = 10; char** paths = malloc(sizeof(char*) * capacity); size_t size = 0; char buffer[MAX_PATH]; while (fgets(buffer, MAX_PATH, file)) { // remove newline character strtok(buffer, "\n"); size++; if (size > capacity) { capacity *= 2; paths = realloc(paths, sizeof(char*) * capacity); } paths[size - 1] = (char*) malloc(strlen(buffer) + 1); strcpy(paths[size - 1], buffer); } fclose(file); char* common_folder = get_deepest_common_folder((const char**)paths, size); printf("Deepest common folder: %s\n", common_folder); free(common_folder); for (size_t i = 0; i < size; i++) { free(paths[i]); } free(paths); return 0; }