Andy
Andy

Reputation: 3

open() function in C

After opening a directory, I wanna check if a command (such as ls) resides within a given directory but open returns an integer i think.. after tokenization, I'm left with some directories... so what can i do?? I was told to use only open() function :((

int       Account_Master;
    .  .  .
  Account_Master = open ("accounts.dat", O_RDONLY);
  if (Account_Master >0) {
    printf ("Open succeeded.\n");

this is the example i used.. whats the point of opening a file if no use?

Upvotes: 0

Views: 4993

Answers (2)

phihag
phihag

Reputation: 287755

The integer returned can be given to other functions, such as read, fstat, and close. If you just want to check whether a file exists, use stat:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
  struct stat statInfo;
  char* fn = argc>1 ? argv[1] : "/bin/ls";
  int res = stat(fn, &statInfo);
  if (res != 0) {
     printf("File %s does not exist.\n", fn);
     return 1;
  }
  if (statInfo.st_mode & S_IXUSR) {
     printf("Owner can execute the file %s\n", fn);
     return 0;
  }
  printf("File %s is there, but not executable.\n", fn);
  return 2;
}

If you don't want to check a single file, but a whole directory, have a look at readdir instead.

Upvotes: 3

Per Johansson
Per Johansson

Reputation: 6877

Homework? If you're only allowed to use open then the solution is to try to open the file. If the call succeeded then the file exists. If it failed, then it doesn't exist.

Edit: strictly speaking, you should also check that errno == ENOENT. Otherwise there was another kind of error preventing you from opening the file.

Don't forget to close the fd returned if the call succeeded.

Btw, the example in your question is not completely correct. open can also succeed by returning 0. It's uncommon though since fd 0 is usually already taken.

Upvotes: 1

Related Questions