Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

COM1407: File Processing

Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Próximo SlideShare
Mesics lecture   files in 'c'
Mesics lecture files in 'c'
Cargando en…3
×

Eche un vistazo a continuación

1 de 48 Anuncio

Más Contenido Relacionado

Anuncio

Más de Hemantha Kulathilake (20)

Más reciente (20)

Anuncio

COM1407: File Processing

  1. 1. COM1407 Computer Programming Lecture 14 File Processing K.A.S.H. Kulathilake B.Sc. (Hons) IT, MCS , M.Phil., SEDA(UK) Rajarata University of Sri Lanka Department of Physical Sciences 1
  2. 2. Objectives • At the end of this lecture students should be able to; ▫ Define the C standard functions for managing file input output. ▫ Apply taught concepts for writing programs. 2
  3. 3. Introduction • The file is the basic unit of storage for many operating systems. • Although C does not have any built-in method for performing file I/O, the C standard library contains a very rich set of I/O functions providing and efficient, powerful and flexible approach. • Those functions can read or write any type of data to files. 3
  4. 4. What is a File? • In C, a file can refer to a disk file and every disk file has a name. • Filenames are stored as strings, just like other text data. • In DOS and Windows 3.X, a complete filename consists of a name that has from one to eight characters, optionally followed by a period and an extension that has from one to three characters. • In contrast, the Windows 95 and Windows NT OS, as well as most UNIX systems, permit filenames upto 256 characters long. 4
  5. 5. What is a File? (Cont…) • A file name in C program also can contain path information. • The path specifies the drive and or directory where the file is located. ▫ C:DATAlist.txt  this is a good programming practice to specify path information. is used to separate the directory names in the path. • If you specify a filename without a path, it will be assumed that the file is located at whatever location the OS currently designates as the default. char* filename = “C:DATAlist.txt”; 5
  6. 6. What is a Stream? • The data flow you transfer from your program to a file, or vice versa, is called a stream which is a series of bytes. • Hence, a stream is a sequence of bytes travelling from a source to a destination over a communication medium. • Streams can either be input or output. • The input stream is used for reading while the output stream is used for writing. • Unlike a file, which targets a specific I/O device, a stream is device independent. • You can perform I/O operations to any type of file by simply associating a stream to the file. 6
  7. 7. What is a Stream? (Cont…) • There are two formats of streams. • Text streams ▫ Consists of sequence of characters. ▫ Depending on the system, each line of characters in a text stream may be terminated by a newline character. ▫ Text streams are used for textual data, which has a consistent appearance from one environment to another, or from one machine to another. 7
  8. 8. What is a Stream? (Cont…) • Binary stream ▫ It consists of series of bytes, e.g., the contents of an executable program file. ▫ Binary streams are primarily used for nentextual data, where the exact contents of the data are maintained without regard to appearance. 8
  9. 9. Buffered I/O • In C, a memory area that is temporarily used to store data before it is sent to its destination is called a buffer. • With the help of buffers, the operating system can improve efficiency by reducing the number of accesses to I/O devices (that is files). • Access to a disk or other I/O device is generally much slower than direct access to memory. • Several I/O operations can be performed on a buffer that represents the I/O file, instead of the file itself. • e.g. if several write operations are sent to a buffer, they are kept in memory until it is time to save, or commit, the new data to the actual device. 9
  10. 10. Pointers of FILE • The FILE structure is the file control structure defined in the header file stdio.h. • A pointer of type FILE is called a file pointer, which references a disk file. • A file pointer is used by a stream to conduct the operation of the I/O function. • e.g. following defines a file pointer called fptr; FILE *fptr; 10
  11. 11. Opening a File • fopen() opens a file and associates a stream with the opened file. #include <stdio.h> FILE *fopen( const char* filename, const char *mode); • Here, filename is a char pointer that references a string containing a filename. • Mode points to another string that specifies the way to open the file. • The fopen() function returns a pointer of type FILE in a success scenario otherwise null pointer is returned. 11
  12. 12. Opening a File (Cont…) 12 Mode Description r Opens an existing text file for reading purpose. w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. r+ Opens a text file for both reading and writing. w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
  13. 13. Opening a File (Cont…) 13 Mode Description rb Opens an existing binary file for reading wb Creates a binary file for writing ab Opens an existing binary file for appending r+b or rb+ Opens an existing binary file for reading or writing w+b or wb+ Creates a binary file for reading or writing a+b ab+ Opens or creates a binary file for appending
  14. 14. Opening a File (Cont…) #include <stdio.h> int main () { FILE *fptr; fptr = fopen("test.txt","r"); if (fptr == NULL ) { printf("Cannot open file.n"); exit (1); } else { printf("File opens successfully.n"); } return 0; } 14
  15. 15. Closing a File • After a disk file is read, written or appended with some new data, you have to disassociate the file from a specified stream by calling the fclose() function. #include <stdio.h> int fclose ( FILE *stream ); • Here stream is a file pointer that is associated with a stream to the opened file. • If fclose() closes a file successfully, it returns 0, otherwise it returns EOF. • Normally, fclose() fails only when the disk is removed before the function is called or there is no more space left on the disk. • The fclose() flushes data left in the buffer to ensure that no data will be lost before it disassociates a specified stream with the opened file. 15
  16. 16. Closing a File (Cont…) #include <stdio.h> int main () { FILE *fptr; fptr = fopen("test.txt","r"); if (fptr == NULL ) { printf("Cannot open file.n"); exit (1); } 16
  17. 17. Closing a File (Cont…) else { int status = 0; printf("File opens successfully.n"); status = fclose(fptr); if (status == 0 ) printf("Status: %i - File closed successfully.n", status); else printf("Error in file closing.n"); } return 0; } 17
  18. 18. I/O Operations • In C, you can perform I/O operations in the following ways; ▫ Read or write one character at a time. ▫ Read or write one line of text at a time. ▫ Read or write one block of characters at a time. 18
  19. 19. Read One Character at a Time • fgetc() fucntion is used to read one character at a time. #include <stdio.h> int fgetc( FILE *stream); • Here stream is the file pointer associated with a stream. • The fgetc() fetches the next character from the stream. • The function then returns value of an int that is converted from the character. • EOF is returned if fgetc() encounters the end of file or if there is an error. 19
  20. 20. Read One Character at a Time (Cont…) #include <stdio.h> int main () { FILE *fptr; char fileName [] = "test.txt"; if ( (fptr = fopen (fileName, "r")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ int c; while ( (c = fgetc(fptr))!= EOF){ putchar (c); } fclose(fptr); } return 0; } 20
  21. 21. Write One Character at a Time • fputc() fucntion is used to write one character at a time. #include <stdio.h> int fputc (int c, FILE *stream); • Here c is an int value that represents a character. • In fact, the int value is converted to an unsigned char before being output. • Stream is the file pointer associated with a stream. • The fputc() returns the character written if the function is successful; otherwise, it returns EOF. • After a character is written, the fputc() advances the associated file pointer. 21
  22. 22. Write One Character at a Time (Cont…) #include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("writec.txt", "w+"); for( ch = 33 ; ch <= 100; ch++ ) { fputc(ch, fp); } fclose(fp); return(0); } 22
  23. 23. Write One Character at a Time (Cont…) #include <stdio.h> #include <string.h> int main () { FILE *fptr; char fileName [] = "writec.txt"; char text[100] = "This content to be written in to a file"; int lstr = strlen( text ); if ( (fptr = fopen (fileName, "w+")) == NULL) { printf("Cannot open file.n"); exit (1); } 23
  24. 24. Write One Character at a Time (Cont…) else { int i; for(i = 0 ; i <= lstr ; i++) fputc (text[i],fptr); printf("End"); fclose(fptr); } return 0; } 24
  25. 25. Activity #include <stdio.h> void charReadWrite( FILE*, FILE*); int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL){ printf("Cannot open %s file.n", fileName1); exit (1); } else{ 25
  26. 26. Activity if ( (fptr2 = fopen (fileName2, "r")) == NULL){ printf("Cannot open %s file.n", fileName2); exit (1); } else{ charReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 26
  27. 27. Activity void charReadWrite( FILE *fin, FILE *fout) { int c; while ((c = fgetc(fin)) != EOF) { fputc(c, fout); putchar(c); } } 27
  28. 28. Read One Line of Text at a Time • fgets() function is used to read one line at a time. #include <stdio.h> char *fgets (char *s, int n, FILE *stream); • Here s refers a character array that us used to store characters read from the opened file pointed to by the file pointer stream. • n specifies the maximum number of array elements. • If it is successful, the fgets() function returns a char pointer s. • If EOF is encountered, the fgets() function returns a null pointer and leaves the array untouched. • If an error occurs, the function returns a null pointer, and the contents of the array are unknown. 28
  29. 29. Read One Line of Text at a Time (Cont…) #include <stdio.h> int main () { FILE *fptr; char fileName [] = "test.txt"; if ( (fptr = fopen (fileName, "r")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ char buff [80]; while ( fgets(buff, 80, fptr)!= NULL){ printf("%s", buff); } fclose(fptr); } return 0; } 29
  30. 30. Read One Line of Text at a Time (Cont…) • The fgets() can read up to n-1 characters, and can append a null character after the last character fetched, until a newline or and EOF is encountered. • Note that the new line is encountered during the read operation, the fgets() function includes the newline in the array. • This is different from what the gets() does. • The gets() just replaces the newline character with a null character. 30
  31. 31. Write One Line of Text at a Time • fputs() function is used to write one line at a time. #include <stdio.h> char *fputs (const char *s, FILE *stream); • Here s points to the array that contains the characters to be written to a file associated with the file pointer stream. • The const modifier indicates that the content of the array pointed to by s cannot be changed by the fputs(). • If it is fails, the fputs() function returns a nonzero value; otherwise, it returns zero. 31
  32. 32. Write One Line of Text at a Time (Cont…) • Note that the character array must include a null character at the end of the string as the terminator to the fputs(). • Also, unlike the puts(), the fputs() does not insert a newline character to the string written to the file. 32
  33. 33. Write One Line of Text at a Time (Cont…) #include <stdio.h> #include <string.h> int main () { FILE *fptr; char fileName [] = "writec.txt"; char text[100] = "This content to be written in to a filen"; int lstr = strlen( text ); if ( (fptr = fopen (fileName, "w+")) == NULL){ printf("Cannot open file.n"); exit (1); } else{ int i=0; for(;i<10;i++) fputs(text, fptr); fclose(fptr); } return 0; } 33
  34. 34. Activity #include <stdio.h> void lineReadWrite( FILE*, FILE*); const int MAX_LEN = 81; int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL) { printf("Cannot open %s file.n", fileName1); } 34
  35. 35. Activity else { if ( (fptr2 = fopen (fileName2, "r")) == NULL) { printf("Cannot open %s file.n", fileName2); } else { lineReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 35
  36. 36. Activity void lineReadWrite( FILE *fin, FILE *fout) { char buff[100]; while ( fgets(buff, MAX_LEN, fin) != NULL) { fputs(buff, fout); printf( "%s", buff); } } 36
  37. 37. Read One Block of Text at a Time • fread() is used to reading one block of text at a time. #include <stdio.h> size_t fread ( void *ptr, size_t size, size_t n, FILE *stream); • Here ptr is a pointer to an array in which the data is stored. • Size indicates the size of each array element. • N specifies the number of elements to read. • Stream is a file pointer that is associated with the opened file for reading. • size_t is a integral type of defined in the header file stdio.h. • The fread() returns the number of elements actually read. 37
  38. 38. Read One Block of Text at a Time (Cont…) • The number of elements read by the fread() function should be equal to the value specified by the third argument to the function, unless an error occurs or and EOF is encountered. • The fread() returns the number of elements that are actually read during the attempt, if an error occurs or an EOF is encountered. 38
  39. 39. Write One Block of Text at a Time • fwrite() is used to write one block of text at a time. #include <stdio.h> size_t fwrite( const void *ptr, size_t size, size_t n,FILE *stream); • Here ptr references the array that contains the data to be written to an opened file pointed to by the file pointer stream. • size indicates the size of each element in the array. • n specifies the number of elements to be written. • The fwrite() function returns the number of elements actually written. • If no error has occurred, the value written by fwrite() should equal the third argument in the function. • The return value may be less than the specified value in an error occurs. 39
  40. 40. Write One Block of Text at a Time (Cont…) • Note that it is programmers’ responsibility to ensure that the array is large enough to hold data for either the fread() or the fwrite(). • In C, a function called feof() can be used to determine when the end of a file is encountered. #include <stdio.h> int feof(FILE *stream); • The feof() returns 0 if the end of the file has not been reached; otherwise, it returns the non zero integer. 40
  41. 41. Write One Block of Text at a Time (Cont…) #include <stdio.h> #include <string.h> int main() { FILE *fp; char c[] = "This is about fread() and fwrite()"; char buffer[100]; /* Open file for both reading and writing */ fp = fopen("file.txt", "w+"); /* Write data to the file */ fwrite(c, strlen(c) + 1, 1, fp); 41
  42. 42. Write One Block of Text at a Time (Cont…) /* Seek to the beginning of the file */ fseek(fp, 0, SEEK_SET); /* Read and display data */ fread(buffer, strlen(c)+1, 1, fp); printf("%sn", buffer); fclose(fp); return(0); } 42
  43. 43. Activity #include <stdio.h> void blockReadWrite( FILE*, FILE*); const int MAX_LEN = 81; int main () { FILE *fptr1, *fptr2; char fileName1 [] = "writec.txt"; char fileName2 [] = "test.txt"; if ( (fptr1 = fopen (fileName1, "w+")) == NULL) { printf("Cannot open %s file.n", fileName1); } 43
  44. 44. Activity else { if ( (fptr2 = fopen (fileName2, "r")) == NULL) { printf("Cannot open %s file.n", fileName2); } else { blockReadWrite (fptr2, fptr1); fclose (fptr1); fclose (fptr2); } } return 0; } 44
  45. 45. Activity void blockReadWrite( FILE *fin, FILE *fout) { int num; char buff[100]; while (!feof(fin)) { num = fread(buff, sizeof(char), MAX_LEN, fin); buff[num * sizeof(char)] = '0'; printf( "%s", buff); fwrite(buff, sizeof(char), num,fout); } } 45
  46. 46. Objective Re-cap • Now you should be able to: ▫ Define the C standard functions for managing file input output. ▫ Apply taught concepts for writing programs. 46
  47. 47. References • Chapter 16 - Programming in C, 3rd Edition, Stephen G. Kochan 47
  48. 48. End of COM1407 Next: Data Structures & Algorithms, Compute Graphics & Image Processing 48

×