25
Text and Binary File Processing Text and Binary File Processing 程程程程 程程程 CCU COMM

Text and Binary File Processing

  • Upload
    sveta

  • View
    72

  • Download
    1

Embed Size (px)

DESCRIPTION

Text and Binary File Processing. 程式設計 潘仁義 CCU COMM. User Program. C Library. OS File System. File. C File I/O Overview(1/3). C File I/O Overview(3/3). - stdio.h 與檔案相關之函式 -. 12.1 Input and Output Files, Review. text file a named collection of characters saved in secondary storage - PowerPoint PPT Presentation

Citation preview

Page 1: Text and Binary File Processing

Text and Binary File ProcessingText and Binary File Processing

程式設計潘仁義

CCU COMM

Page 2: Text and Binary File Processing

C File I/O Overview(1/3)C File I/O Overview(1/3)

C Library

User Program

OS File System

File

Page 3: Text and Binary File Processing

C File I/O Overview(3/3)C File I/O Overview(3/3)

- stdio.h 與檔案相關之函式 -

開啟檔案 FILE *fopen( const char *filename, const char *mode);

存取檔案 int fgetc( FILE *fp );

int fputc( int c, FILE *fp );

int fprintf( FILE *fp, const char *format, … );

int fscanf( FILE *fp, const char *format, … );

size_t fread(void *ptr, size_t size, size_t n, FILE *fp );

size_t fwrite(const void *ptr, size_t , size_t n, FILE *fp );

char *fgets( char *s, int n FILE *fp );

int fputs( const char *s, FILE *fp);

int fseek( FILE *fp, long offset, int whence);

long ftell( FILE *fp );

Int feof(FILE *fp);

關閉檔案 int fclose( FILE *fp);

Page 4: Text and Binary File Processing

12.1 Input and Output Files, Review12.1 Input and Output Files, Review

text filea named collection of characters saved in secondary storage

input (output) streamcontinuous stream of character codes representing textual input (or output) data

(FILE *) stdinsystem file pointer for keyboard’s input stream

(FILE *) stdout, stderrsystem file pointers for screen’s output stream

Page 5: Text and Binary File Processing

TABLE 12.2TABLE 12.2Placeholders for printf Format StringsPlaceholders for printf Format Strings

Placeholder Used for Output of

%c a single character

%s a string

%d an integer (in base 10)

%o an integer (in base 8)

%x an integer (in base 16)

%f a floating-point number

%e a floating-point number in scientific notation

%E a floating-point number in scientific notation

%% a single % sign

Page 6: Text and Binary File Processing

TABLE 12.1 TABLE 12.1 Meanings of Common Escape SequencesMeanings of Common Escape Sequences

Escape Sequence Meaning

‘\n’ new line

‘\t’ tab

‘\f’ form feed (new page)

‘\r’ return (go back to column 1 of current output line)

‘\b’ backspace

語言

Page 7: Text and Binary File Processing

TABLE 12.4 TABLE 12.4 Comparison of I/O with Standard Files and Comparison of I/O with Standard Files and

I/O with User-Defined File PointersI/O with User-Defined File Pointers

Line Functions That Access stdin and stdout

Functions That Can Access Any Text File

1 scanf(“%d”, &num); fscanf(infilep,“%d”, &num);

2 printf(“Number=%d\n”,num); fprintf(outfilep, “Number=%d\n”,num);

3 ch=getchar(); ch=getc(infilep);

4 putchar(ch); putc(ch,outfilep);

Page 8: Text and Binary File Processing

Figure 12.1Figure 12.1 Program to Make a Program to Make a Backup Copy of a Text FileBackup Copy of a Text File

Page 9: Text and Binary File Processing

Figure 12.1Figure 12.1 Program to Make a Program to Make a Backup Copy of a Text File Backup Copy of a Text File (cont’d)(cont’d)

可以換成feof( inp)

嗎 ?不行 , 還是有點不一

Page 10: Text and Binary File Processing

Figure 12.2Figure 12.2 Input and Output Streams Input and Output Streams for File Backup Program for File Backup Program

Page 11: Text and Binary File Processing

File Open ModeFile Open ModeMode Description r Open a file for reading.

w Create a file for writing. If the file already exists, discard the current contents.

a Append; open or create a file for writing at end of file.

r+ Open a file for update (reading and writing).

w+ Create a file for update. If the file already exists, discard the current contents.

a+ Append; open or create a file for update; writing is done at the end of the file.

rb Open a file for reading in binary mode.

wb Create a file for writing in binary mode. If the file already exists, discard the current contents.

ab Append; open or create a file for writing at end of file in binary mode.

rb+ Open a file for update (reading and writing) in binary mode.

wb+ Create a file for update in binary mode. If the file already exists, discard the current contents.

ab+ Append; open or create a file for update in binary mode; writing is done at the end of the file.

Fig. 11.6 File open modes.

Page 12: Text and Binary File Processing

12.2 Binary Files12.2 Binary Files

Formatted Text files contain variable length recordsmust be accessed sequentially, processing all records from the start of file to access a particular record

Binary Files (random access file)a file containing binary numbers that are the computer’s internal representation of each file componentcontain fixed length recordscan be accessed directly, directly accessing the record that is required

Binary files are appropriate for online transaction processing systems, e.g. airline reservation, order processing, banking systems,

sizeofoperator that finds the number of bytes used for storage of a data type

Page 13: Text and Binary File Processing

The Data HierarchyThe Data Hierarchy

Bit - smallest data itemValue of 0 or 1

Byte – 8 bits Used to store a character

Decimal digits, letters, and special symbols

Field - group of characters conveying meaning Example: your name

Record – group of related fieldsRepresented a struct or a classExample: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc.

File – group of related recordsExample: payroll file

Database – group of related files

Page 14: Text and Binary File Processing

In a Random Access File In a Random Access File ……

Data

Data unformatted (stored as "raw bytes") in random access files

All data of the same type (ints, for example) use the same memory

All records of the same type have a fixed length

Data not human readable

Page 15: Text and Binary File Processing
Page 16: Text and Binary File Processing

Random AccessRandom Access

Access individual records without searching through other records

Instant access to records in a file

Data can be inserted without destroying other data

Data previously stored can be updated or deleted without overwriting.Implemented using fixed length records

Sequential files do not have fixed length records0 200 300 400 500

byte offsets}

} } } } } }

100

100bytes

100bytes

100bytes

100bytes

100bytes

100bytes

Page 17: Text and Binary File Processing

Random Access a File -- Random Access a File -- fread ()fread ()

fread --Transfer bytes from a file to a location in memoryFunction fread requires four arguments

ret = fread(buffer, size, num, myptr); the number of objects read

buffer: Address of first memory cell to fill

size: Size of one value

num: Maximum number of elements to copy from the file into memory

myptr: File pointer to a binary file opened in mode “rb” using function fopen

How to distinguish error

and EOF?feof ( ), ferror( )

Page 18: Text and Binary File Processing

Random Access a File Random Access a File –– fwrite() fwrite()

fwrite - Transfer bytes from a location in memory to a filefwrite( &number, sizeof( int ), 1, myPtr );

&number - Location to transfer bytes from

sizeof( int ) - Number of bytes to transfer

1 - For arrays, number of elements to transferIn this case, "one element" of an array is being transferred

myPtr - File to transfer to or from

Page 19: Text and Binary File Processing

Random Access a File Random Access a File –– fwrite() fwrite() (II)(II)

Writing structs

fwrite( &myObject, sizeof (struct myStruct), 1, myPtr );

sizeof - Returns size in bytes of object in parentheses

To write several array elementsPointer to array as first argument

Number of elements to write as third argument

Page 20: Text and Binary File Processing

Figure 12.3Figure 12.3 Creating a Binary File of Creating a Binary File of IntegersIntegers

Page 21: Text and Binary File Processing

Access Data Randomly in a Random Access FileAccess Data Randomly in a Random Access File

fseekSets file position pointer to a specific position

fseek( myPtr, offset, symbolic_constant);myPtr - pointer to file

offset - file position pointer (0 is first location)

symbolic_constant - specifies where in file we are reading from

SEEK_SET - seek starts at beginning of file

SEEK_CUR - seek starts at current location in file

SEEK_END - seek starts at end of file

ftellReturn the current position in a stream

ftell( myptr)myPtr - pointer to file

SEEK_SET SEEK_CUR SEEK_ENDorigin:

目前存取位置 位移後

offset

file

Page 22: Text and Binary File Processing

12.3 SEARCHING A DATABASE12.3 SEARCHING A DATABASE

databasea vast electronic file of information that can be quickly searched using subject headings or keywords

本節請自修 , 寫作業時可參考

Page 23: Text and Binary File Processing

12.4 COMMON PROGRAMMING ERRORS12.4 COMMON PROGRAMMING ERRORS(1/2)(1/2)

Remember to declare a file pointer variable (type FILE *) for each file you want to processfscanf, fprintf, getc and putc must be used for text I/O onlyfread and fwrite are applied exclusively to binary filesgetc, fscanf and fprintf take the file pointer as their first argumentgetc, putc, fread and fwrite take the file pointer as their last argument

Page 24: Text and Binary File Processing

12.4 COMMON PROGRAMMING 12.4 COMMON PROGRAMMING ERRORS (2/2)ERRORS (2/2)

Opening a file for output by calling fopen with a second argument of “w” or “wb” typically results in a loss of any existing file whose name matches the first argument

Binary files cannot be created, viewed, or modified using an editor or word processor program

Depending on OS, a read cannot follow a write, a write cannot follow a read, except using a fseek(fp, 0, SEEK_CUR) between them

Page 25: Text and Binary File Processing

Ch.12 Ch.12 之番外篇之番外篇

懶惰的 C 語言讀取失敗了 , 再來看原因是什麼 ( 別的語言不一定要等到讀失敗 )getc( ) 的 EOF, fread 的傳回 0用 feof( ), ferror( ) 可分辨是 檔案結束 或是 讀取錯誤

想知道檔案的大小嗎 ?fseek( ) + ftell( )stat(), fstat( ), struct stat {... st_size;…};

+ 模式的陷阱交互讀寫可能會有奇怪的現象man fopen

Reads and writes may be intermixed on read/write streams in any order, and do not require an intermediate seek as in previous versions of stdio.This is not portable to other systems, however; ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file.