Thread: Checking File Extensions

  1. #1
    Registered User
    Join Date
    Oct 2008

    Checking File Extensions

    Hey guys. I am currently trying to write a basic encryption/file viewing program for my linux box, and I have run into a small problem while writing it. I want to check to see if the file I am reading in has a .txt extension on it, so that the program will only take .txt files (insures someone doesn't pass some other non-ASCII file.) I have sort of isolated the problem to the code below, which no matter what I do to it, it seems to only output "Non-text file."
    #include <stdio.h>
    #include <string.h>
    int main(){
    	char fn[100]; //String for filename
    	char dump[100]; //Temporary extension test
    	printf("Please enter a filename...\n> ");
    	fgets(fn, sizeof(fn), stdin);
    	fn[strlen(fn)-1] = '\0'; //Remove last \n
    	strcpy(dump, fn); /
    	dump[strlen(dump)-4] = '\0'; //Remove last four characters from dump
    	strcat(dump,".txt"); //Make last four characters of dump .txt for extension checking.
    	if(strcat(dump, fn) == 0){
    		printf("Text file.");
    		printf("Non-text file.");
    Can someone please tell me what I am doing wrong?

    Thanks in advance,

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > if(strcat(dump, fn) == 0)
    Maybe strcmp() is the thing you're after.

    foo.txt just became foo.txtfoo.txt
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2008
    3, that was stupid brilliantly now. Thank you very much.

  4. #4
    C/C++ Learner & Lover
    Join Date
    Aug 2008
    Maybe you can use strtok() using the . as the item to look for and use the extension token and compare it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM