开发者

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜