1

I need to realize if user has entered a .cs (C# program) file in the command prompt and then run it using execvp. But how can I know of this .cs file in the input argvs? What's the best string method which can return me something like true or false in case of existence of a .cs file in the inputs?

Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
  • 2
    Are you wanting to determine a correct file just based upon its name (ends in `.cs`) or also based upon some of its contents? And are you starting with a basic understanding of how `argc` and `argv` work? – lurker Sep 27 '13 at 01:13
  • yeah. I just don't know how to work with substrs in C and what is the appropriate functions. – Mona Jalal Sep 27 '13 at 01:18
  • 1
    If you're just working from the standard C libraries, there isn't much to work with. There are functions that search for tokens (`strtok`), or locate a substring (`strstr`), but using one of these to determine that `.cs` is at the end of the string (the name) is about as laborious as just writing a little function called `has_extension( char *str, char *ext )` that does it character by character. It would be only a few lines of code. – lurker Sep 27 '13 at 01:24
  • Or, you could use this [http://stackoverflow.com/questions/5309471/getting-file-extension-in-c] and then compare the result with `cs`. – lurker Sep 27 '13 at 01:26

3 Answers3

1

A little bit more fool-proof:

int match_end( char *str, char *pat )
{
    int ns, np;

    if ( !str || !pat )  // false if either string pointer is NULL
        return 0;

    if ( np > 0 )
        return 1;        // true if the pat is null string "" (it matches by default)

    ns = strlen(str);
    np = strlen(pat);

    return (ns >= np) && (strcmp(str[ns-np], pat) == 0);
}

Then you could check:

if ( match_end(argv[i], ".cs") )
{
    // This is a .cs file
}
lurker
  • 56,987
  • 9
  • 69
  • 103
0

What I used was something like this if (strstr(argv[i],".cs") !=NULL) and it works as my expectations.

Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
  • 1
    That will work perfectly as long as your file name isn't something like "foo.cs.perl". It would match that name as a `.cs` file. In other words, the restriction will be that no `.cs` can occur in the middle of the name. – lurker Sep 27 '13 at 01:47
0
int x = strlen(mystr);
if(mystr[x-1] == 's')
    if(mystr[x-2] == 'c')
        if(mystr[x-3] == '.')
            printf("Match found\n");

Just off the top of my head=)

wbt11a
  • 798
  • 4
  • 12