fork download
  1. #include <stdio.h>
  2. #include <limits.h>
  3. #include <string.h>
  4.  
  5. #ifndef PATH_MAX
  6. // This is woefully inadequate in normal situations,
  7. // but then on "real" systems (i.e not here inb ideone.com) there would be
  8. // an proper definition, or something similar that should be used instead
  9. # define PATH_MAX 256
  10. #endif
  11.  
  12. int main(void)
  13. {
  14. char full_path[] = "/some/path/to/a/file";
  15.  
  16. // Get the position of the last slash
  17. char *last_slash = strrchr(full_path, '/');
  18.  
  19. // `last_slash` now points to the last slash, or is NULL if none is found
  20. // That means `last_slash + 1` points to the first character in the file-name
  21. // (or to the terminator if the path ends with a slash)
  22.  
  23. // Copy the file-name to another array
  24. char file_name[PATH_MAX];
  25. strcpy(file_name, last_slash + 1);
  26.  
  27. printf("file_name = \"%s\"\n", file_name);
  28.  
  29. return 0;
  30. }
  31.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
file_name = "file"