如何在Pike中获取文件扩展名?寻求类似Python endswith()的方法
endswith() & Extension Extraction) Hey there! Let's tackle how to work with file extensions in Pike, whether you want to check if a filename ends with a specific suffix (like Python's endswith()) or extract the extension directly. Here are a couple of practical, straightforward approaches:
1. Extract the File Extension Directly
If your goal is to pull the extension from a filename (e.g., get pdf from resume.pdf), you can use Pike's built-in string functions to find the last occurrence of the dot (.) and grab everything after it.
Here's a reusable function:
string get_file_extension(string filename) { int last_dot_pos = strrchr(filename, '.'); // Handle edge cases: no dot, or dot is the first character (e.g., .bashrc) if (last_dot_pos <= 0) { return ""; // Return empty string if no valid extension exists } // Return everything after the last dot return substring(filename, last_dot_pos + 1); } // Test it out! write(get_file_extension("project.docx") + "\n"); // Outputs: docx write(get_file_extension("photo.png") + "\n"); // Outputs: png write(get_file_extension(".gitignore") + "\n"); // Outputs: "" (adjust if you want to return gitignore) write(get_file_extension("readme") + "\n"); // Outputs: ""
2. Implement a Python-Style endswith() Function
If you just need to check if a filename ends with a specific suffix (e.g., is this a .txt file?), you can build a simple helper function that mimics Python's endswith() behavior.
bool string_endswith(string target, string suffix) { int target_len = strlen(target); int suffix_len = strlen(suffix); // If the suffix is longer than the target string, it can't match if (suffix_len > target_len) { return 0; } // Compare the end of the target string to the suffix return compare(substring(target, target_len - suffix_len), suffix) == 0; } // Test cases write(string_endswith("logfile.txt", ".txt") ? "Yes\n" : "No\n"); // Yes write(string_endswith("image.jpg", ".png") ? "Yes\n" : "No\n"); // No write(string_endswith("archive.tar.gz", ".gz") ? "Yes\n" : "No\n");// Yes
Quick Notes
- For filenames with multiple dots (like
data.tar.gz), the first function will return the last segment after the final dot (which is usually what you want for file extensions). - Adjust the edge case handling (like
.bashrc) based on your specific needs—if you consider leading dots as valid extensions, just change thelast_dot_pos <= 0check tolast_dot_pos == -1.
内容的提问来源于stack exchange,提问作者mIcHaL MiChAl

