Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting file extension in C

Tags:

c

string

file

How do you get a file extension (like .tiff) from a filename in C?

Thanks!

like image 249
errorhandler Avatar asked Mar 15 '11 09:03

errorhandler


People also ask

What is the file extension for C files?

A CAM file is a CAM (computer-aided manufacturing) data file saved in the FastCAM format. It contains CAD (computer-aided design) information, which includes the processing path and material, thickness, and quantity details of the object. CAM files are similar to . DXF files developed by Autodesk.

How do I show file extensions in CMD?

MS-DOS and Windows command line In MS-DOS, typing dir to list all files also displays the file extension of each file.


3 Answers

const char *get_filename_ext(const char *filename) {     const char *dot = strrchr(filename, '.');     if(!dot || dot == filename) return "";     return dot + 1; }  printf("%s\n", get_filename_ext("test.tiff")); printf("%s\n", get_filename_ext("test.blah.tiff")); printf("%s\n", get_filename_ext("test.")); printf("%s\n", get_filename_ext("test")); printf("%s\n", get_filename_ext("...")); 
like image 112
ThiefMaster Avatar answered Sep 22 '22 14:09

ThiefMaster


Find the last dot with strrchr, then advance 1 char

#include <stdio.h> /* printf */ #include <string.h> /* strrchr */  ext = strrchr(filename, '.'); if (!ext) {     /* no extension */ } else {     printf("extension is %s\n", ext + 1); } 
like image 28
pmg Avatar answered Sep 20 '22 14:09

pmg


You can use the strrchr function, which searches for the last occurrence of a character in a string, to find the final dot. From there, you can read off the rest of the string as the extension.

like image 32
templatetypedef Avatar answered Sep 21 '22 14:09

templatetypedef