课程资源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页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Ch3Ch3LinuxSystem–FileEnyiSoftwareInstituteofNanjingUniversityWhatisFileandFileAnobjectthatcanbewrittento,orreadfrom,orboth.Afilehascertainattributes,includingaccesspermissionsandtype.FileAcollectionoffilesandcertainoftheirattributes.Itprovidesanamespaceforfileserialnumbersreferringtothosefiles.文件系统的多种含FileTypesandFileregularcharacterspecialblockspecialsymbolicFileBytestream;noparticularinternalFileSystemsinVirtualFilesystemSwitchVFSVirtual;onlyexistsinsuperi-nodefiledentryExt2FileExt2HardlinkandsymbolicHard不 文件系Symbolic 文件系Review“lsSystemCalls&LibraryLinux内核的对外接口用户程序和内核之间唯一的接口;提供最小接口依赖于系统调用UnbufferedI/O&BufferedUnbufferedread/write->SystemFileNotinANSIC,butinPOSIX.1andBufferedImplementedinstandardI/O处理很多细节如缓存分配以优化长度执行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(返回值读到的字节数,若已到文件尾为0,若出错为-Writetoafile#includessize_twrite(intfdconstvoid*bufsize_tcount);(返回值:若成功为已写的字节数,若出错为-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为进程设置文件存取权 #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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论