課程資源linux程序設計ch3-1system programming_第1頁
課程資源linux程序設計ch3-1system programming_第2頁
課程資源linux程序設計ch3-1system programming_第3頁
課程資源linux程序設計ch3-1system programming_第4頁
課程資源linux程序設計ch3-1system programming_第5頁
已閱讀5頁,還剩81頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領

文檔簡介

Ch3Ch3LinuxSystem–FileEnyiSoftwareInstituteofNanjingUniversityWhatisFileandFileAnobjectthatcanbewrittento,orreadfrom,orboth.Afilehascertainattributes,includingaccesspermissionsandtype.FileAcollectionoffilesandcertainoftheirattributes.Itprovidesanamespaceforfileserialnumbersreferringtothosefiles.文件系統(tǒng)的多種含F(xiàn)ileTypesandFileregularcharacterspecialblockspecialsymbolicFileBytestream;noparticularinternalFileSystemsinVirtualFilesystemSwitchVFSVirtual;onlyexistsinsuperi-nodefiledentryExt2FileExt2HardlinkandsymbolicHard不 文件系Symbolic 文件系Review“l(fā)sSystemCalls&LibraryLinux內(nèi)核的對外接口用戶程序和內(nèi)核之間唯一的接口;提供最小接口依賴于系統(tǒng)調(diào)用UnbufferedI/O&BufferedUnbufferedread/write->SystemFileNotinANSIC,butinPOSIX.1andBufferedImplementedinstandardI/O處理很多細節(jié)如緩存分配以優(yōu)化長度執(zhí)行I/O等Stream->apointertoBasicI/OSystemFileBasicopen/creat,close,read,write,FileFileAsmallnon-negativeint(inSTDIN_FILENO(0),STDOUT_FILENOSTDERR_FILENOGeneralstepsoffile/*arudimentaryexampleprogram{intfd,nread;charbuf[1024];/*openfile“data”forreading*/fd=open(“data”,O_RDONLY);/*readinthedatanread=read(fd,buf,/*closethefile}Openandpossiblycreateafileor#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>intopen(constchar*pathname,intintopen(constchar*pathname,intflags,mode_tmode);intcreat(constchar*pathname,mode_tmode);(Return:anewfiledescriptorifsuccess;-1ifParameter“flags”:fileaccessOneofO_RDONLY,O_WRONLYorO_RDWRwhichrequestopeningthefileread-only,write-onlyorread/write,respectively,bitwise-or?dwithzeroormoreofthefollowing:(Alldefinedin O_APPEND:thefileisopenedinappendO_TRUNC:Ifthefilealreadyexistsandisaregularfileandtheopenmodeallowswritingwillbetruncatedtolength0.O_CREAT:IfthefiledoesnotexistitwillbeO_EXCL:WhenusedwithO_CREAT,ifthefilealreadyexistsitisanerrorandtheopenwillfail.…“creat”function:equivalenttoopenwithflagsequaltoO_CREAT|O_WRONLY|O_TRUNCParameter“mode”:specifiesthepermissionstouseincaseanewfileiscreated.Thevalueofparameter取 含S_IRGRPS_IXOTH

ReadbyownerWritebyownerExecutebyownerRead,writeandexecutebyReadbygroupWritebygroupRead,writeandexecutebygroupReadbyothersWritebyothersExecutebyothersRead,writeandexecutebyParameter“mode”&umask:afileprotectionTheinitialaccessmodeofanewmode&Closeafile#includeintclose(int(Return:0ifsuccess;-1ifReadfromafile#includessize_tread(intfd,void*buf,size_t(返回值讀到的字節(jié)數(shù),若已到文件尾為0,若出錯為-Writetoafile#includessize_twrite(intfdconstvoid*bufsize_tcount);(返回值:若成功為已寫的字節(jié)數(shù),若出錯為-1)while((n=read(STDIN_FILENO,buf,BUFSIZE))>if(write(STDOUT_FILENO,buf,n)!=err_sys(“writeiferr_sys(“readRepositionread/writefile#include#includeoff_tlseek(intfildes,off_toffset,int(Return:theresultingoffsetlocationifsuccess;-1ifThedirectiveSEEK_SET:theoffsetissetto“offset”SEEK_CUR:theoffsetissettoitscurrentlocation“offset”SEEK_END:theoffsetifsettothesizeofthefileplusDuplicateafile#includeintdup(intintdup2(intoldfd,int(Return:thenewfiledescriptorifsuccess;-1ifFileExample:Manipulateafile#include#includeintfcntl(intfd,intintfcntl(intfd,intcmd,longintfcntl(intfd,intcmd,structflock(返回值:若成功則依賴于cmd,若出錯為-TheoperationisdeterminedbyfcntlFunctionThevalueofF_DUPFD:DuplicateafileexecF_GETOWN/F_SETOWN:ManageI/Oavailabilitydup/dup2andfcntlFunctionThevalueofF_DUPFD:DuplicateafileexecF_GETOWN/F_SETOWN:ManageI/Oavailabilitydup/dup2andControl#includeintioctl(intd,intrequest,StandardI/OFileStandardI/OFileStreamand“FILE”FILE*Predefinedpointer:stdin,stdout,BufferedThreetypesofFullLineNosetbuf/setvbufStreamBufferingThreetypesofblockbuffered(fullylinesetbuf,setvbuf#includevoidsetbuf(FILE*stream,charintsetvbuf(FILE*stream,char*buf,intmode,voidsetbuf(FILE ,charintsetvbuf(FILE*stream,char*buf,inttype,unsignedsize);StandardI/OStreamStream每次一個字符的每次一行的直接I/O(二進制格式化StreamStreamStreamOpena#includeFILE*fopen(constchar*filename,constcharintfclose(FILEParameter Opentextfilefor Truncatefiletozerolengthorcreatetextfile

OpenforOpenforreadingand Openforreadingandwriting.Thefileiscreatedifitdoesnotexist,otherwiseitistruncated. Openforreadingandappending.ThefileiscreateddoesnotStreamopen/closeCloseastream#include<stdio.h>intfclose(FILE*fp);(Return:0ifsuccess;-1ifInputofagetc,fgetc,getchar#include<stdio.h>intgetc(FILE*fp);intfgetc(FILE*fp);intgetchar(void);(Result:Readsthenextcharacterfromastreamreturnsitasanunsignedcharcasttoanint,EOFonendoffileorThreeferror,feof,ungetcfunction:pushacharacterbacktoaOutputofaputc,fputc,putchar#includeintputc(intc,FILE*fp);intfputc(intc,FILE*fp);intputchar(intc);(Return:thecharacterifsuccess;-1ifInputofaLineoffgets,gets#includechar*fgets(char*s,intsize,FILEchar*gets(char fgets:readsinatmostsize-1charactersfromstreamandstoresthemintothebufferpointedbys.ReadingstopsafteranEOForanewline.A?\0?characterisstoredattheendofthebuffer.OutputofaLineoffputs,puts#includeintfputs(constchar*s,FILEintputs(constcharQuestion:I/ORewritegetc/putcBinaryStreamfread/fwrite#includesize_tfread(void*ptr,size_tsize,size_tnmemb,FILEsizefwrite(constvoid*ptr,size_tsize,size_tnmemb,FILE(Return:thenumberofaitemssuccessfullyreadorBinarystreamRead/writeabinaryfloatif(fwrite(&data[2],sizeof(float),4,fp)!=4err_sys(“fwriteRead/writeastructshort long charif(fwrite(&item,sizeof(item),1,fp)!=err_sys(“fwriteFormattedscanf,fscanf,sscanf#includeintscanf(constchar*format,intfscanf(FILE*stream,constchar*format,intsscanf(constchar*str,constchar*format,Usefgets,thenparsetheFormattedI/Oprintf,fprintf,sprintf#includeintprintf(constchar*format,intfprintf(FILE*stream,constchar*format,intsprintf(char*str,constchar*format,Repositionafseek, l,rewind#includeintfseek(FILE*stream,longintoffset,intlong l(FILEvoidrewind(FILEfgetpos,fsetposfunctions(IntroducedinANSI#includeintfgetpos(FILE*fp,fpos_tintfsetpos(FILE*fp,constfpos_tFlusha#includeintfflush(FILEStreamandFile#include<stdio.h>intfileno(FILE#includeFILE*fdopen(intfildes,constcharTemporaryCreateanameforatemporary#includechar*tmpnam(char(返回值:指向唯一路徑名的指針Createatemporary#include<stdio.h>FILE*tmpfile(void);(返回值:若成功為文件指針,若出錯為AdvancedSystemHandlingfileHandlingGetfilestatus#include<sys/stat.h>#include<unistd.h>intstat(constchar*filename,structstatintfstat(intfiledes,structstatintlstat(constchar*file_name,structstat(Return:0ifsuccess;-1ifstructstructstatmode_tst_mode;/*filetype&

/*inodenumber(serialnumber)*/ /*devicenumber(filesystem)*/st_nlink;/*linkcount*/ /*userIDof /*groupIDofowner*/ /*sizeoffile,inbytes*/st_atime;/*timeoflastaccess*/st_mtime;/*timeoflastmodification*/st_ctime;/*timeoflastfilestatus

/*Optimalblocksizefor/*number512-byteblocksTestmacrosforfileDefinedin File

regularcharacterspecialblockspecialsymbolicFilePermission-DeepintoSUID,SGID,StickyFile

含ReadbyownerWritebyownerExecutebyownerRead,writeandexecutebyReadbygroupWritebygroupRead,writeandexecutebyReadbyothersWritebyothersExecutebyothersRead,writeandexecutebyFilepermission

含SetuserIDonexecutionSetgroupIDonexecutionSaved-textbit(stickybit)Example:testingfileif(buf.st_mode&printf(“readablebyprintf(“unreadablebyaccess#includeintaccess(constchar*pathname,intmode);(Return:0ifsuccess;-1iffailure)ParameterR_OK,W_OK,X_OK, odChangepermissionsofa od(constchar*path,mode_tmode);intf od(intfildes,mode_tmode);(Return:0ifsuccess;-1iffailure)Changeownershipofafile#include<sys/types.h>#include<unistd.h>intchown(constchar*path,uid_towner,gid_tgroup);intfchown(intfd,uid_towner,gid_tgroup);intlchown(constchar*path,uid_towner,gid_t(Return:0ifsuccess;-1ifumask為進程設置文件存取權(quán) #include<sys/stat.h>mode_tumask(mode_tCreateanewlinkto(makeanewnamefor)a#includeintlink(constchar*oldpath,constchar (Return:0ifsuccess;-1ifDeleteanameandpossiblythefileitrefers#includeintunlink(constchar*pathname);(Return:0ifsuccess;-1ifCreateasymboliclink(named thcontainsthesting#includeintsymlink(constchar*oldpath,constchar (Return:0ifsuccess;-1ifReadvalueofasymbolic#includeintreadlink(constchar*path,char*buf,size_t(Return:thecountof cedinthebufferif-1ifHandlingchdir/fchdir,Readamkdir/rmdir#include#includeintmkdir(constchar*pathname,mode_t(Return:0ifsuccess;-1if#includeintrmdir(constchar(Return:0ifsuccess;-1ifChangeworking#includeintchdir(constcharintfchdir(int(Return:0ifsuccess;-1if cd(1)getcwd獲得當前工 的絕對路#includechar*getcwd(char*buf,size_t(返回值:若成功則為buf,若出錯則為ReadaDataDIR,structDat

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論