16.05.2015 Views

Working with the Unix OS

Working with the Unix OS

Working with the Unix OS

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

C Libraries<br />

}<br />

if ((fp->flag&( _READ|_EOF|_ERR)) != _READ)<br />

return EOF;<br />

bufsize = (fp->flag & _UNBUF) ? 1: BUFSIZ;<br />

if (fp->base == NULL) /* no buffer yet */<br />

if ((fp->base = (char *) malloc(bufsize) == NULL)<br />

return EOF; /* can't get buffer<br />

fp->ptr = fp->base;<br />

fp->cnt = read(fp->fd, fp->ptr, bufsize);<br />

if (--fp->cnt < 0)<br />

{<br />

if (fp->cnt == -1)<br />

fp->flag |= _EOF;<br />

else<br />

fp->flag |= _ERR;<br />

fp->cnt = 0;<br />

return EOF;<br />

}<br />

return (unsigned char) *fp->ptr++;<br />

Initialization of array _iob:<br />

FILE _iob[OPEN_MAX] = { /* stdin, stdout, stderr */<br />

{ 0, (char *) 0, (char *) 0, _READ, 0 },<br />

{ 0, (char *) 0, (char *) 0, _WRITE, 1 },<br />

{ 0, (char *) 0, (char *) 0, _WRITE | _UNBUF, 2 },<br />

};<br />

Reading Directories<br />

A directory is a list of filenames and an indication of where <strong>the</strong>y are located. The inode for a file is where all<br />

information about a file except its name is kept.<br />

To show a list of files lets write a fsize program (1s), using three routines "opendir", "readdir" and "closedir" to<br />

provide system independent access to <strong>the</strong> name and inode number in a directory entry.<br />

/* dirent.h */<br />

#define NAME_MAX 14 /* longest filename component */<br />

typedef struct{ /* portable directory entry */<br />

long ino; /* inode number */<br />

char name[NAME_MAX+1); /* name + '\0' terminator */<br />

}Dirent;<br />

typedef struct{ /* minimal DIR: no buffering, etc */<br />

int fd; /* file descriptor for directory */<br />

Dirent d; /* <strong>the</strong> directory entry */<br />

}DIR;<br />

DIR *opendir(char *dirname);/* prototypes */<br />

Dirent *readdir(DIR *dfd);<br />

void closedir(DIR *dfd);<br />

The system call "stat" takes a filename and returns all of <strong>the</strong> information in <strong>the</strong> inode for that file, or -1 for an error.<br />

char *name;<br />

struct stat stbuf;<br />

int stat(char *, struct stat *);<br />

stat(name, &stbuf);<br />

Fills <strong>the</strong> structure "stbuf" <strong>with</strong> <strong>the</strong> inode information for <strong>the</strong> file name. This structure is described in<br />

.<br />

70

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!