Opening and Closing Files

Một phần của tài liệu Computer systems a programmers perspective randal e bryant, david r ohallaron (Trang 928 - 932)

A process opens an existing file or creates a.new file by calling the open function. ' .~ < ,...,, ~ ~

#include <sys/types.h>

#include <sys/stat .h> f~~

#include <fcntl.h>

t, 'I I/

int open(char *filename, int' flcigsr,_ mode~t mode);

Returns: new file descriptor if OK, -1 on error

The open function Converts a t'ilename to a file descriptor ana returns the d'e- scriptor number. The 'descriptor returned is always tli'e smallest descriptor that is not currently open in the process. The flags argument indicates ho~'ihe'process

inteIJ,ds to access the file: "

O_RDONLY. Reading only

O _ WRONLY. Writing only ,, O _RDWR. Redding antlwriting

For example, here is how to open an existing file for reading:

fd = Open(11foo. txt11', O_RDONLY, 0) i

l fl hH~• 1

The flags argument canãalso be m~ed with one or more bit masks that provide additional instructions forãwriting:

' '

O_CREAT. If the file doesn't exist, then create a truncated (empty) version, of it.

O_TRUNC. If the file already exists, then truncate it.

O_APPENQ. Before each write operation, set the file position to the end•of the file.

''.

894 Chapter 1 O 'System-Level 1/0 Mask

S_IRUSR S_IWUSR S_IXUSR S_IRGRP S_IWGRP S_IXGRP

Description

User (owner) can read this file User (owner) can write this file

U~er (owner) can execute this file

Members of the owner's group can read this file Members 9f the owner's group can write thi~,file Membprs of the ,owner's group can ex8cute this file S_IROTH

S_IWOTH S_IXOTH

' Others (anyone) can read this file others (anyone) can write this file Others (anyone) can execute this file

Figure 10.2 Access permission bits. petined in sys/stat,-h.

For example, here is how you iniglit open an existing file with the int'enf of appending some data:

fd = Open("foo.txt", O_WRONLYIO_APPEND, 0);

The mode argument specifies the access permission bits of new files. Th~

symbolic names for these bits are shown ip Figure 10.2.

As part .of its context, each procesS< has a umask that is set by calling the umask function. When a process creates a.new file by calling the open function with some mode argument, then the a((~ess permission bits of the file are set to mod,~ & -umask. For eii:ample, s1,1pi;ose we ,are given the following def~l\l\ values

for mode and )lll\ask: ,-, H A' >j ~ Jfj{

#define DEF_MODE S_IRUSRIS_IWUSRIS_IRGRPIS_IWGRPIS_IROTH1S_IWOTH ••

#define DEF_UMASK S_IWGRPIS_IWOTH ,1r

Then the following code fragment creates a new file in which!the owner of the file has read and write permissions, and all other àsers hav~ re~d permission~: ,

umask(DEF_UMASK);

fd = Open("foo.txt", O_C~ATID_TRUNCIO_WRONLY, DEF_MODE<' Finally, a process closes an open file by calling the close function.

J I 'JI.

#include <unistd.h>

int Close(int'fd); ' "' ) _()

Returns: 0 if OK, -1 on error ,_l •

Closing a descrfptonthat is already closed is an error.

Section 10.4 Reading and Writing Files 895

#include 11csap'p.h11

2

3 int main()

4 {

5 int fdl, fd2;

6

7 fdl = Open("foo.txt11, O_RDONLY, O);

8 ciose(fdi);

9 fd2 = Open("baz.txt11, O_RDDNLY, 0);

10 print! ( 11fd2 = %d\n11, fd2);

11 exit(O);

12 }

10.4 R~a.ding and Writing File~

Applications perform input and output by calling the read and write functions, respectively.

#include <unistd.h>

ssize_t read(int fd, void *buf, size_t n);

"'Retllrns: number of bytes read if OK, 0 on EOF, -1 on error ssizeJ.;t "i.rrite(int".fd, const void ~buf, 'Size_t n);

It 'i, l ( I ' •

Returns: number of bytes 'written if OK, -1 on error ' '

The read function t:9pies at mostn'oytes fr6ln the'currbnt file position of descriptor fd to memory JOC,atiori buf'. A return-value of -1 indicates an error, and a return value of o' indicaies EOE C>tlierwise, theãreturh ãvahie indicales the number of

bytes that w,ere.actually transferred. , ,

The write function copies.at most n bytes from memory loc;ation buf to the current file position of descriptor fd. Figure 10.3 shows.a program.that uses read and writ~ calls tp cqpy the standard ipputjo the standard output, l. byre.at a time, Applications can ãexplicitly modify.the current.file position by calling the lseek function, which is beyond our scope.

In some situations, 'read and wri t.e transfer'fewer bY,tes than the application req{\ests. Such short counts do not indicate an error. They occur for a number of reasons:

896 Chapter 10 System-Level 1/0

_,, ,,,,,__,_i'<lal'"_'~iH'!/1""1%'__,'l"""!I""''" " "'J!'l!'.""J!";i'li>"f/;l~"lfrq,"" 11'"""''V ,,,,,,_,,_,, 11"1""'' ã---~---.

Asfde Wb~'vs ttie Bif{erE;hce betweeh ~'Size_t alJ~,size..'.t? , ' ã. '

,._ ãã' • "7<!, { if; "'.:tãã~"l<f)'';'~ ~ .,., ~-ằ<~;,;,.,.. .. ~ftli<i~ '

You inight hiJ.Ve,,n9ti~.eq tha( t~e ~r,.ia<}.l~n~~t~~dn: .. h~&-a~sin~-2¥~ \nput-argument a~d an~~~size_t return, ~ ' '\a!ue, ~'t what's)he d1ffer~nce-between thes,e two.types.?.On xSf/-64 syst~ms, ~ siZe_F 1s c;!efin,ecj ;)S an. !

l unsigned longt\!an(! an s)Sl~e_t lsikned,,,,_si~e)i'S'~O.efined a~ a ~10D.g:'Jbe,,f6acfflln'ftl3if r~lufhs a~si"gn~df"i'

size nitber t)larl ~n,UIJSigl)ed,si~e J:>~<;i\USe jt l,llU~t reJl\rn a -:;f 9n-error.-Inter~sting!y, t~i°.,£JS,si\Jility of

! ,retufni1!~ a-sipg_lp >-1 ~~c;!uyeithe•ma,i<imum sIB_~ of a rea.dlJy ~,fac,tor of:J: 1 -'< ' ã ' ,

__ ..._ ___ "" -~ ,, .. __,,.__...,~.,,.,--"""""-''"""" ~.,, -~"-~~.,,--,,,,;w ,,..,,,,_.,,..,...__.,,._;i:,.,. ~ ,,,,,_,..,, """'~:>/-,,.__,,_,,.,,_ •"'"""'""~~

- - - code/io/cpstdin.c

~include 11csapp.h"

2

3 int main(void)

4 {

5 char c;

6

7 while(Read(STDIN_FILEND, &c, 1) != 0) 8 Write(STDOUT_FILENO, &:c, 1);

9 exit(O);

10 }

- - - code!iolcpstdin.c Figure 10.3 Using read and write to copy standard input to standard output 1 byte at a time.

Encountering EOF on reads. Supppse that we are ready to read from a file that contains only 20 more bytes from the current file position and that we are reading the file jn 50-byte chunks. Then the,next ã;read will returl} a short cou\lt of 20, and.the read after tha~.wjll signal EOF by returning a short count of 0.

Readin8 text lines from. a.Jerminal. J~ the 9p1>n fil~ is ass}lciated with a terminal (i.e.,!\ keyboard anq display), then,faph reaq funcliop w,ill,trHn~fer one text line at a time, returàing a short cqunt equal to tp.e size of th'f te,xt line.

Reading and writing network sockets. If the open file corresponds to a network

"ã socke!J (Section lt:4), then internal buffering,comitraints and long net- ,, work.d"ela31s can cause read and write to return short counts:Short counts

1 >.can also occur when-you call read.and write on a Linux pipe, an inter-

"process'communication mechahism that is beyond our scope.

r

.,, In practice, you will never encounter short countsãwhen you read. from disk files except on EOF, and ¥ou will never encounter short counts when you write to disk files. However, if you want to build robust (reliable) network applications

Section 10.5 Robust Reading and Writing with the R16 Package 897

such asã Web servers, then you: must deal.with short courits- by repeatedly calling reaqGmd write until all requested bytes have been•transferred11

" .,,

Một phần của tài liệu Computer systems a programmers perspective randal e bryant, david r ohallaron (Trang 928 - 932)

Tải bản đầy đủ (PDF)

(1.120 trang)