+ All Categories
Home > Documents > ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial...

ECE 103 Engineering Programming Chapter 44 File I/O Herbert G. Mayer, PSU CS Status 6/4/2014 Initial...

Date post: 14-Dec-2015
Category:
Upload: august-blankenship
View: 216 times
Download: 0 times
Share this document with a friend
29
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
Transcript
Page 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.

ECE 103 Engineering ProgrammingChapter 44

File I/O

Herbert G. Mayer, PSU CSStatus 6/4/2014

Initial content copied verbatim fromECE 103 material developed by

Professor Phillip Wong @ PSU ECE

Page 2: 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.

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

Page 3: 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.

3

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

Page 4: 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.

4

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.

Page 5: 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.

5

Text file storage format:

Binary file storage format:

12316351840

31 32 33 0a 31 36 33 35 31 38 34 30 0a

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 82 60 Hex - Assuming big-endian format

Page 6: 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.

6

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.

Page 7: 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.

7

File I/O the "C" Way

File I/O prototypes are declared in <stdio.h> .( #include <stdio.h> )

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.

Page 8: 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.

8

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.

Page 9: 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.

9

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.

Mode If file exists If file does not exist

"r" Opens the file for reading Error

"w" Opens a new file for writing Creates a new file

"a" Opens the file for appending Creates a new file

"r+" Opens the file for reading & writing Error

"w+" Opens a new file for reading & writing Creates a new file

"a+" Opens the file for reading & appending Creates a new file

Page 10: 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.

10

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 */

Page 11: 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.

11

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.

Page 12: 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.

12

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 */

Page 13: 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.

13

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.

Page 14: 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.

14

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.

Page 15: 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.

15

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.

Page 16: 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.

16

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)

Page 17: 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.

17

Algorithm for Reading Files with fscanf()

1. Attempt to open the file2. Check that the file successfully opened

3. For each value in the file, read it in using fscanf()4. Attempt to close the file5. Check that the file successfully closed

Page 18: 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.

18

Example:/* Program for reading from a text file */#include <stdio.h>

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.42.0 3.73.0 4.2

Output:

1.0 3.42.0 3.73.0 4.2

Page 19: 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.

19

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

Page 20: 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.

20

Algorithm for Writing Files with fprintf()

1. Attempt to open the file2. Check that the file opened successfully

3. For each data value, write it out using fprintf()

4. Attempt to close the file5. Check that the file closed successfully

Page 21: 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.

21

Example:

Sample data stored within out.txt:

Test filex is 5

/* Program for writing to a text file */#include <stdio.h>

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;}

Page 22: 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.

22

Example:/* Output operation: choose file or console */#include <stdio.h>#include <stdlib.h>

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 <stdio.h>#include <stdlib.h>

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;

}

Page 23: 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.

23

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).

Page 24: 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.

24

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 macro Set origin of offset to Sign 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).

Filestart end

file position

Page 25: 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.

25

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.

Page 26: 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.

26

Example:/* Perform file I/O - Text file version */#include <stdio.h>#include <stdlib.h>#include <math.h>

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.0000001 1.0000002 1.4142143 1.7320514 2.000000

Reading text data ...0 0.0000001 1.0000002 1.4142143 1.7320514 2.000000

Page 27: 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.

27

Example:/* Perform file I/O - Binary file version */#include <stdio.h>#include <stdlib.h>#include <math.h>

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.0000001 1.0000002 1.4142143 1.7320514 2.000000

Reading binary data ...0 0.0000001 1.0000002 1.4142143 1.7320514 2.000000

Page 28: 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.

28

Example:/* Perform file I/O - Binary file version */#include <stdio.h>#include <stdlib.h>#include <math.h>

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): 33 1.732051

Page 29: 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.

29

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.030 30 30 30 30 0a 32 20 31 2e 34 31 34 32 31 34 00000□2 1.4142140a 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.0000001 1.0000002 1.4142143 1.7320514 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 0000 00 00 00 00 00 f0 3f 02 00 00 00 cd 3b 7f 669e a0 f6 3f 03 00 00 00 aa 4c 58 e8 7a b6 fb 3f04 00 00 00 00 00 00 00 00 00 00 40

(int:4 bytes + double:8 bytes) per line*(5 lines) = 60 bytes


Recommended