1、LOGOChapter Seven FileFileChapter SevenContents Introduction1Open/close file2Read/write file 3 Check the state of the opening file4The location of the file pointer54Chapter SevenHow to get the data while run a program?Where will the result in ?How can input the result of a program to another program
2、 ? Introduction The procedure of C language EditLinkCompile Chapter Seven Introductionprogram format outputcharacter outputstring outputinitializationassignment input from keyboardmemorymemoryformat inputcharacter inputstring input Read data from a file Write data to a fileChapter Seven Introduction
3、 File is the gather of related information saved in memory device (assistant memory ) OS manages system in files Processing files means file input/out processing.Procedure 1 open file2 file read/write 3 close file.Interface input/out devices are treated as files in C .File accessing methods: 1) Buff
4、ered I/O (or stream I/O) 2) Unbuffered I/O (or low-level I/O)Chapter Seven IntroductionBuffered (temporary storage location) Well discuss Buffered I/O in our lecture In buffered I/O,-open a communication area in RAMDISkPROGRAMOutput file buffer Input file bufferThere are two ways to deal with file:B
5、inary fileASCII file Chapter Seven Introduction Stream is the abstract of file used to deal with file. There are two kinds of streams in C. The character is ASCII code .one ASCII code occupies one byte , new line n is end of line .After read /write a character from /to ASCII file , the fp increases
6、automatically to guarantee the read /write sequences.Text streamBinary streamStoring data to disk in the form the same as in RAM .Example : 10000 In binary file , use 2 bytes In ASCII file , use 5 bytesChapter SevenOpen/close fileHow to magange a file in C ?PointerOperations open file(load file )ope
7、rate file using functionsclose file (remove file from memory)A file system creat a new filedelete an old oneread/write access a file by its namemanage the memory file usedlimit the users rightChapter SevenOpen/close file File pointer,points to a structure that contains information about the file, su
8、ch as the location of a buffer , the current character position in the buffer, whether the file is being read or written, and whether errors or end of file have occurred. Users dont need to know the details ,because the definitions obtained from include a structure declaration called FILE. I am a st
9、udent .Chapter Seven 2 The function of opening a file :FILE *fp; uppercase letters ,otherwise ,cant be recognized, defined to standard structure , key-word # include is necessary fopen ( filename ,*mode );stringchar arraychar pointer paths are allowed 1 files pointer :opening a file use function fop
10、en ( ) readwriteappendOpen/close fileChapter SevenOpen/close filefp=fopen (“ file.txt ” , “r ” );open file.txt , read in ASCIIOpening a file means.returns a file pointerspecify the operation to be done points to the first location of file buffer.r-readfile.txtwhich The returned value is assigned to
11、a file pointer.Chapter Seven If process is successful , the returned value is a file pointer. (address ) FLIE *fp; Otherwise, return NULL pointer.if ( ( fp = fopen ( “file.txt” “r ” ) = = NULL ) printf ( “ cant open file n”); exist (1 ) ; Open/close fileSymbolExplanationrreadwwriteaappendtText strea
12、mbBinary stream+Permit read/write If fopen fails , return value is zero ( NULL pointer) when: 1)fopen wants to open a non existed file for reading .2) read a file not permitted read .3) create a file but disk is full . 4) disk sector is bad .Chapter Seven3 Close a fileClose a file opened ,argument &
13、 a pointer to file to be closed in order to 1) release fp and 2) clean up the buffer.fclose ( fp );Open/close file Opened file must be closed before ending a program, otherwise, data may be lost .Chapter Seven Writes string into file pointed by stream File read/writefgets(string,n,stream) Reads a st
14、ring of up to n-1 characters from stream and places them into stringfputs(string, stream) 1 read/write file functionsfgetc (fp), fputc(fp) read/write a char from /to file read : c = fgetc(fp); read a char from named file.write : fputc (c,fp ); write c to named file.Prototype in stdio.h return EOF (-
15、1) if a) at the end of file; b) detecting an error;Using function fgets() and fputs() can realize string input/ouput in files.Chapter Seven main ( int argc, char *argv ) int c ; FILE *fpr, *fpd; if ( argc!=3) putchar(007); puts( Usage: copy file1, file 2); exit( ); if ( (fpr=fopen (argv1 ,r) = NULL
16、) printf(%c,007); printf(file %s cant open n, argv 1); exit( ); if ( fpd = fopen ( argv2 ,w )= NULL) printf ( files %s cant openn , argv2); exit ( ); while( c=fgetc(fpr)!= EOF) fputc(c, fpd); fclose (fpr); fclose (fpd);Input three strings( file name)Source file name object file name The function of
17、this program is to copy file1 to file2Chapter Seven#includemain() FILE *fp; char c1;fp=fopen(“file.dat”,”r”); c1=fgetc(fp);putchar(c1); fclose(fp);#includemain() FILE *fp; char ch=a;fp=fopen(“file.dat”,”w”);fputc(ch,fp);fclose(fp); Read the character from file.dat write character a to file.dat . Fil
18、e read/writefscanf ( stream, format , arg,.) Reads data from stream using format conversion specifier into address specifierd by arg .fprintf (stream,format, arg,.) Writes arg into stream using format conversion specifier.Chapter Sevenmain( ) FILE *fp; char *c1=“Turbo C”; char c210; fp=fopen(“file2.
19、dat”,”w”); fputs(c1,fp); fclose(fp); fp=fopen(“file2.dat”,”r”); fgets(c2,8,fp); printf(“%sn”,c2); fclose(fp); File read/write read a string from determined file (fp) , have read 7 chars;Returned value: normal the 1st location of the string; error or end of file NULLwrite a string to determined file
20、(fp)Returned value: normal: the number of chars; error : NULLChapter Sevenmain() FILE *fp; char *c1=“Turbo C”; char c210; fp=fopen(“file3.dat”,”w”); fprintf(fp,”%s”,c1); fclose(fp); fp=fopen(“file3.dat”,”r”); fscanf(fp,”%s”,c2); printf(“%sn”,c2); fclose(fp); File read/writeIt is similar to printf ,
21、add fp file pointerIt is similar to scanf, add fp file pointerChapter Sevenmain( ) FILE *fp; char str81, filename80; gets(filename); if(fp=fopen(filename,”w”)=NULL) printf(“can not open this filen”); exit(0); while(strlen(gets(str)0 ) fputs(str,fp); fputs(“n”,fp); fclose(fp); Input several strings ,
22、 then save them to diskCan you use “filename” here ?How many strings should you input ? File read/writeChapter Seven fread reads n items of size length from stream into buffer. File read/write fwrite( ) / fread( ) * Two standard library functions are available to facilitate the storage of data array
23、s in binary forms. These are fwrite( ) and fread( ).fwrite( buffer, size, n, stream); fread( buffer, size, n, stream); buffer :a pointer to the start of the buffer to be written into stream. n: items in the buffer of length size in bytes.Chapter Seven when computer are started, 3 standard files are
24、opened automatically, and 3 associated file pointers are provided 。 User neednt write statements to open standard files and after program are executed,standard files automatically closed.2 Interface input/out devices stdin file inputstdout standard output pointerstderr error exit(1) : return to os .
25、 Innormal exist exit(0) : - normal exist .3 Exit functions program will stop right away. File read/writeChapter SevenThe files state is necessary when using input/out functions ,especially testing the end of a file. There are one couple of ways to test the end of file1 EOF When reading /writing ASCI
26、I file, EOF is used to test if the file pointer points to the end of file, if so, the value of EOF is -1 Cant suit for binary file 2 function feof ( ) feof(file pointer name ) The return value is nonzero at the end of file ,Otherwise , it is not the end of file .Check the state of the opening file C
27、hapter Sevenwhile(feof(fp)=0) c=fgetc(fp);Check the state of the opening file while(c=fgetc(fp)!=EOF) putchar( c ); Example : read characters from a file Chapter SevenThe location of he file pointer1 rewind Sets file pointer to stream to beginning of file2 fseek Locates file pointer for stream at of
28、fset bytes from origins fseek(file pointer name ,offsets,origin ) No return value Generally it is Used for binary file0:the begining1:current position 2:the end The number of bytes + move backwards- move forwards return: a zero if the pointer was reset without error.Chapter Seven3、 The current posit
29、ion Returns current position of file pointed from stream Return 1L means there is something wrong The location o f the file pointerWhere is the current position of the file pointer? 0 Beginning of file 1 Current position of file pointer 2 End of fileChapter Sevenmain ( int argc, char *argv ) char s8
30、0; int a; FILE *fp; if ( (fp=fopen (test ,w) = NULL ) printf(cant open file ); exit( ); fscanf(stdin, %s%d, s, &a); /*read from keyboard*/ fprintf(fp, %s %d, s, a); /* write to file*/ fclose(fp); if ( (fp=fopen (test ,r) = NULL ) printf(cant open file ); exit( ); fscanf(fp , %s%d, s, &a); /*read fro
31、m file*/ fprintf(stdout, %s %d, s, a); /* print on screen*/ fclose(fp);The location o f the file pointerChapter Seven /* Writing an array of data using fwrite FWRITE.C*/ #include main( ) static int buffer = 70,71,72,73,74,75,76,77,78,79,80,81,82,83 ; FILE *fp; int i; fp = fopen(testdata,w); fwrite(c
32、har *)buffer, 2, 14, fp); fclose(fp); The location o f the file pointerChapter Seven /* fread.c */ #include main( ) FILE *fp; static int buffer14; int i; fp = fopen(testdata,r); fread(char *)buffer, 2, 14, fp); fclose(fp); for (i=0; i14; i+) printf(%dn,bufferi); The location o f the file pointerChap
33、ter Seven main( ) static char buffer = abcdefg; long pick; long offset; char c; FILE *fp; fp = fopen(testdata,w); fwrite(buffer,1,7,fp); fclose(fp); fp = fopen(testdata, r); for( pick = 3; pick 7; pick+) fseek(fp, pick, 0); offset = ftell(fp); fscanf(fp, %c,&c); printf( data item at offset %ld is %cn, offset, c); fclose(fp); The location o f the file pointerLOGO