Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #99142

Re: C newb - Part III - find a .jhr file in a directory - seg fault

From Ben Bacarisse <ben.usenet@bsb.me.uk>
Newsgroups comp.lang.c
Subject Re: C newb - Part III - find a .jhr file in a directory - seg fault
Date 2016-12-12 22:18 +0000
Organization A noiseless patient Spider
Message-ID <87k2b4pzac.fsf@bsb.me.uk> (permalink)
References <azB3A.89805$dL2.72348@fx12.iad>

Show all headers | View raw


S390 <s390@tampascanner.info> writes:
<snip>
> I am lost at this point... why the test for the *.jhr file fails and seg 
> faults...
>
>
> $ cat dirtest.c 
>
> #include <dirent.h> 
> #include <stdio.h> 
> #include <string.h>
>
> int main(void)
> {
>   char hdrfile;
>   int len;
>   const char ch = '.';
>   char *ret;
>   DIR           *d;
>   struct dirent *dir;
>   d = opendir(".");
>   if (d)
>   {
>     while ((dir = readdir(d)) != NULL)
>     {
>      ret = strchr(dir->d_name, ch);

When the name does not have a '.' in it, the result will be a null
pointer -- a special value that does not point at anything, often used
to indicate failure in some way.  Doing anything with a null pointer is
a Bad Thing, but printf:

>      printf("String after |%c| is - |%s|\n", ch, ret);

tries to help but printing (null), but this test

>      if (strcmp(ret,".jhr") != 0)

Will almost certainly go wrong.

>         printf("%s\n", dir->d_name);
>     }
>
>     closedir(d);
>   }
>
>   return(0);

<snip>
-- 
Ben.

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

C newb - Part III - find a .jhr file in a directory - seg fault S390 <s390@tampascanner.info> - 2016-12-12 17:58 +0000
  Re: C newb - Part III - find a .jhr file in a directory - seg fault Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-12-12 22:18 +0000
    Re: C newb - Part III - find a .jhr file in a directory - seg fault S390 <s390@tampascanner.info> - 2016-12-20 22:12 +0000
      Re: C newb - Part III - find a .jhr file in a directory - seg fault Barry Schwarz <schwarzb@dqel.com> - 2016-12-20 14:38 -0800

csiph-web