code_junkie

How to get file extension from string in C++

Nov 10th, 2011
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <iostream>
  2. #include<string>
  3.  
  4. int main()
  5. {
  6. std::string fn = "filename.conf";
  7. if(fn.substr(fn.find_last_of(".") + 1) == "conf") {
  8. std::cout << "Yes..." << std::endl;
  9. } else {
  10. std::cout << "No..." << std::endl;
  11. }
  12. }
  13.  
  14. std::string filename("filename.conf");
  15. std::string::size_type idx;
  16.  
  17. idx = filename.rfind('.');
  18.  
  19. if(idx != std::string::npos)
  20. {
  21. std::string extension = filename.substr(idx+1);
  22. }
  23. else
  24. {
  25. // No extension found
  26. }
  27.  
  28. std::string GetFileExtension(const std::string& FileName)
  29. {
  30. if(FileName.find_last_of(".") != std::string::npos)
  31. return FileName.substr(FileName.find_last_of(".")+1);
  32. return "";
  33. }
  34.  
  35. System::String^ GetFileExtension(System::String^ FileName)
  36. {
  37. int Ext=FileName->LastIndexOf('.');
  38. if( Ext != -1 )
  39. return FileName->Substring(Ext+1);
  40. return "";
  41. }
  42.  
  43. #include <ctype.h>
  44. #include <string.h>
  45.  
  46. int main()
  47. {
  48. char filename[] = "apples.bmp";
  49. char extension[] = ".jpeg";
  50.  
  51. if(compare_extension(filename, extension) == true)
  52. {
  53. // .....
  54. } else {
  55. // .....
  56. }
  57.  
  58. return 0;
  59. }
  60.  
  61. bool compare_extension(char *filename, char *extension)
  62. {
  63. /* Sanity checks */
  64.  
  65. if(filename == NULL || extension == NULL)
  66. return false;
  67.  
  68. if(strlen(filename) == 0 || strlen(extension) == 0)
  69. return false;
  70.  
  71. if(strchr(filename, '.') == NULL || strchr(extension, '.') == NULL)
  72. return false;
  73.  
  74. /* Iterate backwards through respective strings and compare each char one at a time */
  75.  
  76. for(int i = 0; i < strlen(filename); i++)
  77. {
  78. if(tolower(filename[strlen(filename) - i - 1]) == tolower(extension[strlen(extension) - i - 1]))
  79. {
  80. if(i == strlen(extension) - 1)
  81. return true;
  82. } else
  83. break;
  84. }
  85.  
  86. return false;
  87. }
Add Comment
Please, Sign In to add comment