Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed.

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed."— Presentation transcript:

1 ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

2 Syllabus Introduction to File I/O Opening and Closing Files Character File I/O String File I/O Formatted File I/O Direct I/O

3 2 Introduction to File I/O Definition → A computer file is data that is stored on some form of durable medium. Basic file operations:  read – data is retrieved from a file  write – data is stored to a file  append – data is added to the end of a file

4 3 Major types of files:  Text Readable by humans (e.g., ASCII characters) More portable across systems Has end-of-line issues (Unix:LF, MSWin:CR+LF)  Binary Usually is not readable by humans (binary coding) Less portable across systems Has endian issues The efficiency of text versus binary depends on the type and amount of data stored in the file.

5 4 Text file storage format: Binary file storage format: 123  16351840  31 3233 0a 31 3633 35 31 3834 300a Each character is 1 byte wide. Total storage = 13 bytes '1''2''3''\n''1''6''3''5''1''8''4''0''\n' ASCII Hex Suppose 123 (hex 7b) is stored as type char (1 byte) Suppose 16351840 (hex 00f98260) is stored as type int (4 bytes) Total storage = 5 bytes 7b 00 f9 8260 Hex - Assuming big-endian format

6 5 Follow these steps when using file I/O functions:  Open the file Establishes I/O channel and enables access Only need to open file once  Read, write, or append to the file Perform as many operations as needed  Close the file Saves pending data and closes down channel Closed files can be re-opened again Multiple files can be open at the same time. Each file will have its own unique ID.

7 6 File I/O the "C" Way File I/O prototypes are declared in. ( #include ) When a file is opened, a unique file pointer is assigned to it. File pointers are of type FILE *. Declaration: FILE *fp; where fp is a pointer variable name.

8 7 A file pointer variable contains the address of a structure that holds file information. A file pointer is passed as an argument to a file I/O function to let it know which file to access. Another name for a file pointer is file handle.

9 8 Opening a File FILE * fopen (const char * filename, const char * mode); This function opens a file for read/write/append access. filename is a string with the name of the file to open. mode is a string containing the desired opening mode. A file pointer is returned. ModeIf file existsIf file does not exist "r" Opens the file for readingError "w" Opens a new file for writingCreates a new file "a" Opens the file for appendingCreates a new file "r+" Opens the file for reading & writingError "w+" Opens a new file for reading & writingCreates a new file "a+" Opens the file for reading & appendingCreates a new file

10 9 A binary file is opened by appending a ”b” to the mode. Example: fp = fopen("file.dat","rb"); /* Open binary file */ If successful, the assigned file pointer is returned. If not successful, the NULL value is returned. Always test the return value for NULL. Example: fp = fopen("myfile.txt","r"); if (fp == NULL) /* An error occurred */ printf("File open not successful\n"); else /* File opened OK */

11 10 Closing a File int fclose (FILE * fp); When a file is no longer needed, this function closes it. fp is the file pointer of the file to close. If successful, a zero (0) value is returned. If not successful, the EOF value is returned. The fclose() function ensures that any data still in the output buffer is written to the file before actually closing.

12 11 Test the return value to verify the operation’s success. Example: status = fclose(fp); if (status == EOF) /* An error occurred */ printf("File close not successful.\n"); else /* File closed OK */

13 12 Character File I/O Functions int fgetc (FILE * fp);  This reads a single character from a file.  If successful, the next character from the file is read in and returned (converted to type int). If not successful, the EOF value is returned. int fputc (int ch, FILE * fp);  This writes the character ch to a file.  If successful, the character written is returned. If not successful, the EOF value is returned.

14 13 String File I/O Functions char * fgets (char * str, int num, FILE * fp);  This reads a string from a file.  Up to num characters are read and then stored in str.  If successful, str is returned. If not successful, the NULL value is returned. int fputs (const char * str, FILE * fp);  This writes the string str to a file.  If successful, a non-negative value is returned. If not successful, the EOF value is returned.

15 14 Formatted File I/O Functions int fscanf (FILE * fp, const char * format, …);  This works just like scanf().  If successful, the # of items read is returned. If not successful, the EOF value is returned. int fprintf (FILE * fp, const char * format, …);  This works just like printf().  If successful, the # of characters written is returned. If not successful, a negative value is returned.

16 15 Status & Error Functions int feof (FILE * fp);  This checks if the end of the file has been reached.  Returns a non-zero value only if the previous read attempt failed. Miscellaneous C has several predefined file pointer values:  stdin-Standard input (console)  stdout-Standard output (console)  stderr-Standard error (console)

17 16 Algorithm for Reading Files with fscanf() 1. Attempt to open the file 2. Check that the file successfully opened 3. For each value in the file, read it in using fscanf() 4. Attempt to close the file 5. Check that the file successfully closed

18 17 Example: /* Program for reading from a text file */ #include int main (void) { FILE *ifile;/* Input file pointer */ float x, y;/* Input variables */ if ((ifile = fopen("data.txt","r")) == NULL) printf("File open not successful.\n"); else { /* Read values and display them */ while (fscanf(ifile,"%f %f",&x,&y) != EOF) printf("%.1f %.1f\n", x, y); if (fclose(ifile) == EOF) printf("File close not successful.\n"); } return 0; } Sample data.txt: 1.0 3.4 2.0 3.7 3.0 4.2 Output: 1.0 3.4 2.0 3.7 3.0 4.2

19 18 Conceptual file operations: 1.0 3.4 2.0 3.7 3.0 4.2 end scanf()==EOF → F x → 1.0 y → 3.4 Iteration #1 scanf()==EOF → F x → 2.0 y → 3.7 Iteration #2 1.0 3.4 2.0 3.7 3.0 4.2 end scanf()==EOF → F x → 3.0 y → 4.2 Iteration #3 1.0 3.4 2.0 3.7 3.0 4.2 end scanf()==EOF → T Exit Loop Iteration #4 1.0 3.4 2.0 3.7 3.0 4.2 end

20 19 Algorithm for Writing Files with fprintf() 1. Attempt to open the file 2. Check that the file opened successfully 3. For each data value, write it out using fprintf() 4. Attempt to close the file 5. Check that the file closed successfully

21 20 Example: Sample data stored within out.txt: Test file x is 5 /* Program for writing to a text file */ #include int main (void) { FILE *ofile;/* Output file pointer */ float x = 5; const char *s = "x is"; if ((ofile = fopen("out.txt","w")) == NULL) printf("File open not successful.\n"); else { /* Write out values */ fprintf(ofile, "Test file\n"); fprintf(ofile, "%s %d\n", s, x); if (fclose(ofile) == EOF) printf("File close not successful.\n"); } return 0; }

22 21 Example: /* Output operation: choose file or console */ #include int main (void) { FILE *fp; /* File pointer */ int mode, k; printf("File or console (f/c)? "); mode = getchar(); getchar(); printf("Enter integer: "); scanf("%d", &k); if (mode == 'f') { /* Output to file */ if ((fp = fopen("d.txt","w")) == NULL) { printf("Open error.\n"); exit(0); } else /* Output to console */ fp = stdout; printf("Writing data...\n"); fprintf(fp, "%d", k); fclose(fp); return 0; } /* Input operation: choose file or console */ #include int main (void) { FILE *fp; /* File pointer */ int mode, k; printf("File or console (f/c)? "); mode = getchar(); getchar(); if (mode == 'f') { /* Input from file */ if ((fp = fopen("d.txt","r")) == NULL) { printf("Open error.\n"); exit(0); } else /* Input from console */ fp = stdin; printf("Reading data...\n"); fscanf(fp, "%d", &k); printf("data = %d\n", k); fclose(fp); return 0; }

23 22 Direct I/O Functions size_t fread (void * ptr, size_t size, size_t nobj, FILE * fp);  Reads nobj number of objects, each of size size from file fp and stores them at address ptr.  The # of objects read is returned. size_t fwrite (const void * ptr, size_t size, size_t nobj, FILE * fp);  Writes nobj number of objects, each of size size, that are stored at address ptr to file fp.  The # of objects written is returned. The sizeof() operator returns the size of an object. Example: sizeof(int) returns 4 (int type is 4 bytes).

24 23 int fseek (FILE * fp, long int offset, int origin);  This sets the file position for fp. Subsequent reads or writes begin at the new position.  On error, non-zero is returned. origin macroSet origin of offset toSign of offset SEEK_SET Start of file+ SEEK_CUR Current position+ or - SEEK_END End of file- For binary files: file position = origin + offset For text files: offset must be zero, or a value return by ftell (and then origin must be SEEK_SET ). File startend file position

25 24 long ftell (FILE * fp);  This returns the current file position within fp.  If successful, current file position is returned On error, -1 is returned. void rewind (FILE * fp);  This resets the file position to the start of the file.

26 25 Example: /* Perform file I/O - Text file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double sr, y;/* Holds calc values */ /* Write data to text file */ if ((fp = fopen("tfile.txt","w")) == NULL) { printf("Error opening output file.\n"); exit(0); } printf("Writing text data...\n"); for (k = 0; k < 5; k++) { sr = sqrt(k); printf("%d %f\n", k, sr); fprintf(fp, "%d %f\n", k, sr); } fclose(fp); /* Read data from text file */ if ((fp = fopen("tfile.txt","r")) == NULL) { printf("Error opening input file.\n"); exit(0); }; printf("\nReading text data...\n"); for (k = 0; k < 5; k++) { fscanf(fp, "%d %lf", &x, &y); printf("%d %f\n", x, y); } fclose(fp); return 0; } Writing text data... 0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000 Reading text data... 0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000

27 26 Example: /* Perform file I/O - Binary file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double sr, y;/* Holds calc values */ /* Write data to binary file */ if ((fp = fopen("bfile.bin","wb")) == NULL) { printf("Error opening output file.\n"); exit(0); } printf("Writing binary data...\n"); for (k = 0; k < 5; k++) { sr = sqrt(k); printf("%d %f\n", k, sr); fwrite(&k, sizeof(k), 1, fp); fwrite(&sr, sizeof(sr), 1, fp); } fclose(fp); /* Read data from binary file */ if ((fp = fopen("bfile.bin","rb")) == NULL) { printf("Error opening input file.\n"); exit(0); }; printf("\nReading binary data...\n"); for (k = 0; k < 5; k++) { fread(&x, sizeof(x), 1, fp); fread(&y, sizeof(y), 1, fp); printf("%d %f\n", x, y); } fclose(fp); return 0; } Writing binary data... 0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000 Reading binary data... 0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000

28 27 Example: /* Perform file I/O - Binary file version */ #include int main (void) { FILE *fp;/* File pointer */ int k, x;/* Holds indep values */ double y;/* Holds calc values */ /* Read data from binary file */ if ((fp = fopen("bfile.bin","rb")) == NULL) { printf("Error opening input file.\n"); exit(0); } printf("Enter index to read (0 to 4): "); scanf("%d", &k); rewind(fp); fseek(fp, k*(sizeof(x)+sizeof(y)), SEEK_SET); fread(&x, sizeof(x), 1, fp); fread(&y, sizeof(y), 1, fp); printf("%d %f\n", x, y); fclose(fp); return 0; } Enter index to read (0 to 4): 3 3 1.732051

29 28 Example: Saved as Text file (hex view) 30 20 30 2e 30 30 30 30 30 30 0a 31 20 31 2e 30 0 0.000000□1 1.0 30 30 30 30 30 0a 32 20 31 2e 34 31 34 32 31 34 00000□2 1.414214 0a 33 20 31 2e 37 33 32 30 35 31 0a 34 20 32 2e □3 1.732051□4 2. 30 30 30 30 30 30 0a.00000□ Saved as Text file (ASCII view) 0 0.000000 1 1.000000 2 1.414214 3 1.732051 4 2.000000 ((10 characters+'\n')*(1 byte/character)) per line*(5 lines) = 55 bytes Saved as Binary file (hex view) 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 00 f0 3f 02 00 00 00 cd 3b 7f 66 9e a0 f6 3f 03 00 00 00 aa 4c 58 e8 7a b6 fb 3f 04 00 00 00 00 00 00 00 00 00 00 40 (int:4 bytes + double:8 bytes) per line*(5 lines) = 60 bytes


Download ppt "ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed."

Similar presentations


Ads by Google