I have this in a code:
`

int load_snapshot(char *fname, int files)
{
  FILE *fd;
  char buf[200];
  int i, j, k, dummy, ntot_withmasses;
  int t, n, off, pc, pc_new, pc_sph;

#define SKIP fread(&dummy, sizeof(dummy), 1, fd);

  for(i = 0, pc = 1; i < files; i++, pc = pc_new)
    {
      if(files > 1)
    sprintf(buf, "%s.%d", fname, i);
      else
    sprintf(buf, "%s", fname);

      if(!(fd = fopen(buf, "r")))
    {
      printf("can't open file `%s`\n", buf);
      exit(0);
    }

      printf("reading `%s' ...\n", buf);
      fflush(stdout);

      fread(&dummy, sizeof(dummy), 1, fd);
      fread(&header1, sizeof(header1), 1, fd);
      fread(&dummy, sizeof(dummy), 1, fd);

And i don´t know why the program returns can't open file. I dn´t know how can I do to avoid fd = fopen(buf, "r")

Recommended Answers

All 3 Replies

It looks to me that fopen doesn't return true or false, it returns a pointer, which is null on fail. See if this helps:

fd = fopen(buf, "r");
if(fd != NULL)

And i don´t know why the program returns can't open file.

fopen sets errno on failure, which you can query to find out why. The easiest way here would be to interpret the error code using strerror:

if(!(fd = fopen(buf, "r")))
{
    printf("can't open file `%s`: %s\n", buf, strerror(errno));
    exit(0);
}

Make sure to include <cerrno> or <errno.h> and <cstring> or <string.h>.

It looks to me that fopen doesn't return true or false, it returns a pointer, which is null on fail.

True, but when taken in boolean context, the pointer will be true if not null and false if null, so the code as originally given is fine. From a stylistic standpoint, I prefer your version though. ;)

"The nice thing about standards, is that there are so many!"

So, when writing code, be clear, explicit, and consistent!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.