/* * Path resolver program * * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://www.wtfpl.net/ for more details. */ #include #include #include #include #include #include char* resolve_path(const char* input) { char* resolved_path = malloc(PATH_MAX); if (!resolved_path) { perror("Memory allocation failed"); exit(EXIT_FAILURE); } // ケース1: 入力が '.' または '/' で始まる場合 if (input[0] == '.' || input[0] == '/') { if (realpath(input, resolved_path) == NULL) { perror("realpath failed"); free(resolved_path); return NULL; } return resolved_path; } // ケース2: 環境変数PATHからファイルを探す char* path_env = getenv("PATH"); if (!path_env) { fprintf(stderr, "PATH environment variable not found\n"); free(resolved_path); return NULL; } // PATHを:で分割して処理 char* path_copy = strdup(path_env); char* path_token = strtok(path_copy, ":"); struct stat st; while (path_token != NULL) { char full_path[PATH_MAX]; snprintf(full_path, PATH_MAX, "%s/%s", path_token, input); // ファイルが存在するか確認 if (stat(full_path, &st) == 0) { if (realpath(full_path, resolved_path) == NULL) { perror("realpath failed"); free(path_copy); free(resolved_path); return NULL; } free(path_copy); return resolved_path; } path_token = strtok(NULL, ":"); } free(path_copy); free(resolved_path); return NULL; } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return EXIT_FAILURE; } char* result = resolve_path(argv[1]); if (result) { printf("%s\n", result); free(result); return EXIT_SUCCESS; } else { fprintf(stderr, "File not found: %s\n", argv[1]); return EXIT_FAILURE; } }