英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 14 - Files

4Lecture 14What is a file?atandotoAfile isdata stored in secondary storage·This isusualadisk (hard/floppy/optical etc)connectedtothecomputerbusbymeansofsomeinterface.Accessing data in files is much slowerthanfrommemory,butfilesaremorepermanentand can be largerathndDitaSrudCesiteygeStreams inCStreamsinC:To use a file we must first open a stream, when we.InCeachfileisassociatedwithabufferarefinished the streammustbe closedto forma stream.When is included in a program,3streamsareautomaticallyopenedAbufferissimplyanareaofmemory stdin, stdout, stderrthatisusedfortemporarystorage.They arespecial in that theyarenormally·This is because it is more efficienttoconnected tothekeyboard and screen ratherthanmovedatato/fromfilesin"chunks"a disk file however as weve already seen they canberedirectedbuffer:When theprogramhasfinished runningthesestreamstreamsareautomaticallyclosedFileStructureDirectories,pathsandfilenames·Most operating systems organise secondary.Thereare2sortsoffilestorageinatreestructureusingdirectories--textfileswhichuseASCll codesto storetextdatabinary files whichare usedto store rawbinarydata:Adirectoryisafilecontainingthenamesofotherfiles and where theyare stored.Inthiscoursewewillonlydealwithtextfiles·Eachfile is identifiedbya filenamemyfile.cfilenamebeginning of file/Thisisafile*/[n]:Its location isgivenbya path#include[(n][In]e.g./usr/students/1996/a.Person/c/myfile.clines oftextmain() [\n]areCtolytre(In): If"C" is the current directory we can refer to the filen]simply as"myfile.c"or we can give the full pathend-of-fle marker[EOF]
1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 14 Lecture 14 What is a file? • A file is data stored in secondary storage • This is usual a disk (hard/floppy/optical etc) connected to the computer bus by means of some interface • Accessing data in files is much slower than from memory, but files are more permanent and can be larger Streams in C • In C each file is associated with a buffer to form a stream • A buffer is simply an area of memory that is used for temporary storage • This is because it is more efficient to move data to/from files in “chunks” buffer stream file Streams in C • To use a file we must first open a stream, when we are finished the stream must be closed • When is included in a program, 3 streams are automatically opened – stdin, stdout, stderr • They are special in that they are normally connected to the keyboard and screen rather than a disk file however as weve already seen they can be redirected • When the program has finished running these streams are automatically closed Directories, paths and filenames • Most operating systems organise secondary storage in a tree structure using directories. • A directory is a file containing the names of other files and where they are stored • Each file is identified by a filename • Its location is given by a path • e.g. /usr/students/1996/A.Person/C/myfile.c • If “C” is the current directory we can refer to the file simply as “myfile.c” or we can give the full path root of directory tree director filename File Structure • There are 2 sorts of file – text files which use ASCII codes to store text data – binary files which are used to store raw binary data • In this course we will only deal with text files myfile.c /* This is a file*/[\n] #include [\n] [\n] main()[\n] {[\n] }[\n] [EOF] file name beginning of file lines of text end-of-file marker

0100Files in Cd seou cssueedos+ +有. pin aw.:?In C,a stream is identified with a pointer-to-FILEhisiah a rraana-datatypeHereFILE is a specialdata type defined in o aod et4La2442442FILpfilei/-pointer-to-rILe,or stream-/,010.Wethenhave topoint itata particular file18pfile-fopen("myfile.c","r"); /- r stands for read -/.Functionfopenisdeclaredinby招--谐tauo馆the prototype热区...ILEy Fopen(gons char filenaney Const chart mods);ASmgPaeoAS.. 20“Bomb-Proofing"fileOperations.O8b p 1 31 Unfortunately there are many things that can.SoPISO1Sgo wrong.44-Supposewetrytoopenafileforwriting(which。 的dgenerally creates a new file) but the file alreadyDPunoy e+uo ue oy * uda 4 n 2 2exists with read-only permission. In this case the fopen will return NULL 0 T We cant write to a NULL streamUE E To avoid the program crashing we should alwaysimegmecheck the result of file operationsaed .[Pz4daCopying a file.This is like the unix cp command. We want to be8Rableto enterandcopymyfile.cto anotherBranplercopyingatile*the e alt'epy tenteecA·PoorprogramASwith no bombnt main(intChar *argr[1)argcacopy1.c1proofing.Son relarie elets improve:O01电auane:p:taBlonit华Ee1生(i) n2
2 Files in C • In C, a stream is identified with a pointer-to-FILE datatype • Here FILE is a special data type defined in FILE *pfile; /* pointer-to-FILE, or stream */ • We then have to point it at a particular file pfile=fopen(“myfile.c”,”r”); /* r stands for read */ • Function fopen is declared in by the prototype FILE* fopen(cons char* filename, const char* mode); Pointer to file A String A String • There are several other functions for file operations see notes pg 73 /* Example: simple file operations */ /* No error checking is done, so the program may fail! All practical programs should check file operations. */ #include #include int main(void) { FILE *pf; /* file pointer, or stream */ char str[40]; int n; char c; pf = fopen("myfile.old", "w"); /* open a file for writing */ fputs("Hello world!\n", pf); /* write to the file */ fclose(pf); /* close the file */ rename("myfile.old", "myfile.new"); /* rename the file */ pf = fopen("myfile.new", "a"); /* open file for appending */ fprintf(pf, "Hello again! "); /* write string */ fprintf(pf, "%i ", 123); /* write number */ fputc('#', pf); fputc('\n', pf); /* write characters */ fclose(pf); /* close the file */ pf = fopen("myfile.new", "r"); /* open file for reading */ fgets(str, 40, pf); /* read a line */ printf(str); /* print it to the screen */ rewind(pf); /* rewind file to start */ fgets(str, 40, pf); /* read a line */ printf(str); /* print it to the screen */ fscanf(pf, "%s", str); /* read a word */ printf(str); /* print it to the screen */ putchar('\n'); fscanf(pf, "%s", str); /* .another word */ printf("%s\n", str); fscanf(pf, "%i", &n); /* .a number */ printf("%i\n", n); c = fgetc(pf); putchar(c); /* .some characters */ c = fgetc(pf); putchar(c); c = fgetc(pf); putchar(c); fclose(pf); /* close the file */ remove("myfile.new"); /* delete the file */ return EXIT_SUCCESS; } /* Example: simple file operations */ /* No error checking is done, so the program may fail! All practical programs should check file operations. */ #include #include int main(void) { FILE *pf; /* file pointer, or stream */ char str[40]; int n; char c; pf = fopen("myfile.old", "w"); /* open a file for writing */ fputs("Hello world!\n", pf); /* write to the file */ fclose(pf); /* close the file */ rename("myfile.old", "myfile.new"); /* rename the file */ pf = fopen("myfile.new", "a"); /* open file for appending */ fprintf(pf, "Hello again! "); /* write string */ fprintf(pf, "%i ", 123); /* write number */ fputc('#', pf); fputc('\n', pf); /* write characters */ fclose(pf); /* close the file */ pf = fopen("myfile.new", "r"); /* open file for reading */ fgets(str, 40, pf); /* read a line */ printf(str); /* print it to the screen */ rewind(pf); /* rewind file to start */ fgets(str, 40, pf); /* read a line */ printf(str); /* print it to the screen */ fscanf(pf, "%s", str); /* read a word */ printf(str); /* print it to the screen */ putchar('\n'); fscanf(pf, "%s", str); /* .another word */ printf("%s\n", str); fscanf(pf, "%i", &n); /* .a number */ printf("%i\n", n); c = fgetc(pf); putchar(c); /* .some characters */ c = fgetc(pf); putchar(c); c = fgetc(pf); putchar(c); fclose(pf); /* close the file */ remove("myfile.new"); /* delete the file */ return EXIT_SUCCESS; } file1.c file1.c “Bomb-Proofing” file Operations • Unfortunately there are many things that can go wrong. – Suppose we try to open a file for writing (which generally creates a new file) but the file already exists with read-only permission. – In this case the fopen will return NULL – We cant write to a NULL stream – To avoid the program crashing we should always check the result of file operations /* Example: standard file operations, with error checking */ /* All practical programs should check file operations. */ #include #include #define STR_SIZE 40 int main(void) { FILE *pf; /* file pointer, or stream */ char str[STR_SIZE], name[] = "myfile.tmp"; /* open a file for writing: */ pf = fopen(name, "w"); /* pf is NULL if an error occurs */ if (pf == NULL) { fprintf(stderr, "Error opening file %s for writing\n", name); exit(EXIT_FAILURE); } fputs("Hello world!\n", pf); /* write to the file */ fclose(pf); /* close the file */ /* open a file for reading: */ pf = fopen(name, "r"); /* pf is NULL if an error occurs */ if (pf == NULL) { fprintf(stderr, "Error opening file %s for reading\n", name); exit(EXIT_FAILURE); } fgets(str, STR_SIZE, pf); /* read a line */ printf(str); /* print it to the screen */ fclose(pf); /* close the file */ return EXIT_SUCCESS; } /* Example: standard file operations, with error checking */ /* All practical programs should check file operations. */ #include #include #define STR_SIZE 40 int main(void) { FILE *pf; /* file pointer, or stream */ char str[STR_SIZE], name[] = "myfile.tmp"; /* open a file for writing: */ pf = fopen(name, "w"); /* pf is NULL if an error occurs */ if (pf == NULL) { fprintf(stderr, "Error opening file %s for writing\n", name); exit(EXIT_FAILURE); } fputs("Hello world!\n", pf); /* write to the file */ fclose(pf); /* close the file */ /* open a file for reading: */ pf = fopen(name, "r"); /* pf is NULL if an error occurs */ if (pf == NULL) { fprintf(stderr, "Error opening file %s for reading\n", name); exit(EXIT_FAILURE); } fgets(str, STR_SIZE, pf); /* read a line */ printf(str); /* print it to the screen */ fclose(pf); /* close the file */ return EXIT_SUCCESS; } file2.c file2.c It is useful to send error messages to stderr rather than stdout If stdout is redirected, stderr still connects to the screen Copying a file • This is like the unix cp command. We want to be able to enter and copy myfile.c to another /* Example: copying a file */ /* Like Unix's cp command. When compiled, rename a.out to copy, then use as: copy filename newname */ /* Warning: THIS SKELETON VERSION CONTAINS NO BOMB-PROOFING! */ #include int main(int argc, char *argv[]) { FILE *poldfile, *pnewfile; int byte; poldfile = fopen(argv[1], "r"); /* open existing file */ pnewfile = fopen(argv[2], "w"); /* open new file */ while ((byte = fgetc(poldfile)) != EOF) fputc(byte, pnewfile); } /* Example: copying a file */ /* Like Unix's cp command. When compiled, rename a.out to copy, then use as: copy filename newname */ /* Warning: THIS SKELETON VERSION CONTAINS NO BOMB-PROOFING! */ #include int main(int argc, char *argv[]) { FILE *poldfile, *pnewfile; int byte; poldfile = fopen(argv[1], "r"); /* open existing file */ pnewfile = fopen(argv[2], "w"); /* open new file */ while ((byte = fgetc(poldfile)) != EOF) fputc(byte, pnewfile); } • Poor program with no bomb proofing. So lets improve on it copy1.c copy1.c copy2.c copy2.c /* Example: copying a file */ /* Like Unix's cp command. When compiled, rename a.out to copy, then use as: copy filename newname */ /* This version has pretty good bomb-proofing */ #include #include int main(int argc, char *argv[]) { FILE *poldfile, *pnewfile; int byte; /* check the arguments: */ if (argc != 3) /* argv[0] is the program's name */ { fprintf( stderr, "Error: 2 arguments expected\n"); exit(EXIT_FAILURE); } /* open the files: */ poldfile = fopen(argv[1], "r"); /* open existing file */ if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (read)\n", argv[1]); exit(EXIT_FAILURE); } pnewfile = fopen(argv[2], "w"); /* open new file */ if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (write)\n", argv[2]); exit(EXIT_FAILURE); } /* do the copying: */ while (1) { int check; byte = fgetc(poldfile); if (byte == EOF) /* copying completed */ break; check = fputc(byte, pnewfile); if (check == EOF) /* write error */ { fprintf(stderr, "Error: file %s (write)\n", argv[2]); exit(EXIT_FAILURE); } } /* Example: copying a file */ /* Like Unix's cp command. When compiled, rename a.out to copy, then use as: copy filename newname */ /* This version has pretty good bomb-proofing */ #include #include int main(int argc, char *argv[]) { FILE *poldfile, *pnewfile; int byte; /* check the arguments: */ if (argc != 3) /* argv[0] is the program's name */ { fprintf( stderr, "Error: 2 arguments expected\n"); exit(EXIT_FAILURE); } /* open the files: */ poldfile = fopen(argv[1], "r"); /* open existing file */ if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (read)\n", argv[1]); exit(EXIT_FAILURE); } pnewfile = fopen(argv[2], "w"); /* open new file */ if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (write)\n", argv[2]); exit(EXIT_FAILURE); } /* do the copying: */ while (1) { int check; byte = fgetc(poldfile); if (byte == EOF) /* copying completed */ break; check = fputc(byte, pnewfile); if (check == EOF) /* write error */ { fprintf(stderr, "Error: file %s (write)\n", argv[2]); exit(EXIT_FAILURE); } } /* verify the copy: */ fclose(pnewfile); pnewfile = fopen(argv[2], "r"); if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (read)\n", argv[2]); exit(EXIT_FAILURE); } rewind(poldfile); while (1) { byte = fgetc(poldfile); if (byte == EOF) /* verification completed */ break; if (byte != fgetc(pnewfile)) /* copy error */ { fprintf(stderr, "Error: file %s is corrupt\n", argv[2]); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; } /* verify the copy: */ fclose(pnewfile); pnewfile = fopen(argv[2], "r"); if (poldfile == NULL) { fprintf(stderr, "Error: couldn't open file %s (read)\n", argv[2]); exit(EXIT_FAILURE); } rewind(poldfile); while (1) { byte = fgetc(poldfile); if (byte == EOF) /* verification completed */ break; if (byte != fgetc(pnewfile)) /* copy error */ { fprintf(stderr, "Error: file %s is corrupt\n", argv[2]); exit(EXIT_FAILURE); } } return EXIT_SUCCESS; }

Example:StudentMarksFilen n7,gPtaatilda.hmarks1.csyew.First well createhosa sda file of student,names andmarksOProsep.1* +6*.0 - + 0)a& aB :DOAWR RETRAnt!Proe0re的entmaieseoygw2Rnant 5.neeroI, inope o eep spd -/ANPLEPP EHSears'w x p 1+wE1sum IPTOA91S.3
3 • First well create a file of student names and marks /* Example: writing data to a file */ #include #include #define DATA "class.list" int main(void) { FILE *pf; char surname[7][20] = {"SMITH", "JONES", "BLOGGS", "GASCOIGNE", "BLAIR", "MAJOR", "ASHDOWN"}; char forename[7][20] = {"Jane", "Blodwyn", "Frederick", "Paul", "Anthony", "John", "Patrick"}; int mark[7] = {47, 73, 27, 65, 68, 70, 54}; int s; pf = fopen(DATA, "w"); /* open new file */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* write the data to file: */ for (s = 0; s #include #define DATA "class.list" int main(void) { FILE *pf; char surname[7][20] = {"SMITH", "JONES", "BLOGGS", "GASCOIGNE", "BLAIR", "MAJOR", "ASHDOWN"}; char forename[7][20] = {"Jane", "Blodwyn", "Frederick", "Paul", "Anthony", "John", "Patrick"}; int mark[7] = {47, 73, 27, 65, 68, 70, 54}; int s; pf = fopen(DATA, "w"); /* open new file */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* write the data to file: */ for (s = 0; s #include #define DATA "class.list" #define CLASS 7 int main(void) { FILE *pf; char surname[CLASS][20]; char forename[CLASS][20]; int mark[CLASS]; int s; pf = fopen(DATA, "r"); /* open file to read */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* read data from the file: */ for (s = 0; s #include #define DATA "class.list" #define CLASS 7 int main(void) { FILE *pf; char surname[CLASS][20]; char forename[CLASS][20]; int mark[CLASS]; int s; pf = fopen(DATA, "r"); /* open file to read */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* read data from the file: */ for (s = 0; s #include #define DATA "class.list" #define MAX_CLASS 10 int main(void) { FILE *pf; char surname[MAX_CLASS][40]; char forename[MAX_CLASS][40]; int mark[MAX_CLASS]; int s, lines; pf = fopen(DATA, "r"); /* open file to read */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* read data from the file: */ for (s = 0; !feof(pf); s++) /* stop at end of file */ { if (s >= MAX_CLASS) { fputs("Error: too many lines in file\n", stderr); exit(EXIT_FAILURE); } fscanf(pf, "%s %s %i", &surname[s], &forename[s], &mark[s]); } lines = s - 1; fclose(pf); /* print data to stdout: */ for (s = 0; s #include #define DATA "class.list" #define MAX_CLASS 10 int main(void) { FILE *pf; char surname[MAX_CLASS][40]; char forename[MAX_CLASS][40]; int mark[MAX_CLASS]; int s, lines; pf = fopen(DATA, "r"); /* open file to read */ if (pf == NULL) { fprintf(stderr, "Error: couldn't open file %s\n", DATA); exit(EXIT_FAILURE); } /* read data from the file: */ for (s = 0; !feof(pf); s++) /* stop at end of file */ { if (s >= MAX_CLASS) { fputs("Error: too many lines in file\n", stderr); exit(EXIT_FAILURE); } fscanf(pf, "%s %s %i", &surname[s], &forename[s], &mark[s]); } lines = s - 1; fclose(pf); /* print data to stdout: */ for (s = 0; s < lines; s++) printf("%s %s got %i%%\n", forename[s], surname[s], mark[s]); return EXIT_SUCCESS; } marks3.c marks3.c
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 13 - More functions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 12 - Basics of Functions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 11 - Strings.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 10 - Basics of Pointers.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 9 - Arrays.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 3 - Hardware and Software.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 8 - Looping.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 7 - Making Decisions.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 6 - Operators, Expressions and Statements.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 5 - Standard IO.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 4 - Simple Data Types.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 2 - Binary Representation.pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 1 - Introduction.pdf
- 《计算机程序设计基础》课程学习指南(C语言)给C语言初学者的学习建议.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-2/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言初学者编程规范-1/2.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见问题详解.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见英文单词.pdf
- 《计算机程序设计基础》课程学习指南(C语言)C语言常见错误中英文对照表.pdf
- 《计算机程序设计基础》课程教学大纲 C Programming Language(C语言).pdf
- 英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 15 - Data Structures.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第1章 C语言概述.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第2章 基本数据类型和运算符.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第3章 控制结构.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第4章 数组和指针.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第5章 模块化编程.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第6章 指针进阶与内存空间管理.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第7章 结构体与共同体.pdf
- 《计算机程序设计基础》课程授课教案(C语言)第8章 数据文件编程方法.pdf
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-10 IO函数值和注释语句.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-8 标识符和关键字.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-11 编程风格与常见错误.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-9 输入输出函数.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-7 实例求圆柱体底面积和体积.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-5 第1个C程序解析.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-6 预处理指令#define#include.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-4 算法的表示.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-1 C语言的概述.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-2 结构化程序设计方法.ppt
- 《计算机程序设计基础》课程PPT教学课件(C语言)第1章 C语言概述 1-3 算法的概念和特点.ppt