51
Input/Ouput Chap 22

Input/Ouput Chap 22. 2 22.1 Streams Stream means any source of input or any destination for output. A file pointer is used to access a stream. FILE *fp1,

  • View
    214

  • Download
    1

Embed Size (px)

Citation preview

Input/Ouput

Chap 22

2

22.1 Streams

• Stream means any source of input or any destination for output.

• A file pointer is used to access a stream.FILE *fp1, *fp2;

• Standard streamsFile Pointer Stream Default Meaningstdin Standard input Keyboardstdout Standard output Screenstderr Standard error Screen

3

Opening a File (22.2)

• Syntax:FILE *filePtr = fopen(fileName, mode);

– filePtr is a variable of a file pointer, a pointer to a FILE-structure object.

–mode: read ( 讀檔 ), write ( 寫檔 ), append ( 追加 );text ( 文字檔 ), binary 檔 . (See next page)

• Ex:

FILE *fptr = fopen("mydata.txt", "r");

4

Opening a File

• mode in fopen():– "r":

• If the file does not exit, file opening fails;• Otherwise open it.

– "w":• If the file exists, current content will be discarded;• If the directory in the file name does not exist,

file opening fails;• Otherwise, create a new file for writing.

5

Opening a File

• Table of file open modes ( 開啟模式 ):Mode 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.

6

Opening a File

• ASCII mode ( 純文字模式 ):– fopen()預設是 ASCII 模式– 讀入 DOS 換行符號 "\r\n" (\x0d0a) 時,會自動改成 '\n'

– 寫出 '\n'時也會改為 "\r\n"– '\0' 會被視為字串結尾

• Binary mode:– 在 fopen()中以 "rb", "wb", etc. 開啟檔案– 影片檔、圖片檔、甚至 MSWord 檔都應該以 binary 格式存取。

7

Opening a File

• fopen()– On failure, fopen()returns NULL.

• It is a good habit to check if the return value is NULL whenever you open a file.

• Ex:FILE *fptr = fopen("mydata.txt", "r");if (fptr == NULL){ printf(" 開檔失敗 \n"); exit(0);}

8

Closing a File (22.2)

• Syntax:fclose(FILE * filePtr);– Ex:FILE *fptr = fopen("mydata.txt", "r");// handling files here, then...fclose(fptr);

– fclose()returns memory allocated for this file pointer

– If you open too many files without closing it, your program will crash.

9

Checking end-of-file (22.2)

• Syntax:feof(FILE * filePtr);– Returns true if the end-of-file indicator of the

stream for this file pointer is set.

10

22.5 Line I/O

• fgets(char *str, int size, FILE *fptr)– Read in one line from a file.– If end-of-file is found, returns NULL.

• Ex:FILE *fptr = fopen("mydata.txt", "r");char buf[1000];while (fgets(buf, sizeof(buf), fptr)!= NULL){ // buf 是新讀入的一行文字 }

• fputs(const char *str, FILE *fptr)– Write a line into a file.

11

22.3 Formatted I/O

• fscanf(FILE *fptr, …scanf-params… ) – Same format and usage as scanf(), but its

first parameter is a FILE pointer and the input comes from this file.

• fprintf(FILE *fptr, …printf-params…) – Same format and usage as printf(), but its

first parameter is a FILE pointer and the output is stored in this file.

Formatted Input/Output

Section 22.3

13

printf()

• printf(format string, other arguments);

• Format specification:%[flags] [width] [.precision] [{h | l | I64 | L}]type

Ex: printf( "%+3.5lf", 4.56);

14

Printing Integers ( 整數 )

– 負數會印出負號來ConversionSpecifier

Description

d Display a signed decimal integer.i Display a signed decimal integer. (Note: The i and d

specifiers are different when used with scanf.)o Display an unsigned octal integer.u Display an unsigned decimal integer.x or X Display an unsigned hexadecimal integer. X causes the digits

0-9 and the letters A-F to be displayed and x causes thedigits 0-9 and a-f to be displayed.

h or l (letter l) Place before any integer conversion specifier to indicate thata short or long integer is displayed respectively. Letters hand l are more precisely called length modifiers .

一般

八進位制unsigned

十六進制

長短整數

15

Printing Floating-Point Numbers(浮點數 )• %f – 印浮點數 , 小數點前至少一位 , 小數點後六位• %e, %E – 科學記號表示法 Exponential notation

(computer's version of scientific notation)– 150.3 的科學記號表示法是 1.503 x 10²– 電腦改以 1.503E+002 表示 (E 表 exponent)– 可規定大小寫 e or E

• %g (or %G) – 選 %f or %e (%E), 後面不補零 (1.2300 只印出 1.23)– 選 %e: 指數小於 -4, 或大於等於 precision ( 預設 6 位 )– 選 %f: 其他情形

16

Printing Strings and Characters• %c: 字元 character

• %s: 字串 string

• 請注意– 字元以一對 single quotes 表示 ('z')– 字串以一對 double quotes 表示 ("z")

17

Other Conversion Specifiers

• %p– 印出位址格式

• %%– 印出百分比號 (%)

回 printf

18

Field Widths 欄位寬度• 設定欄寬所用• 預設是靠右對齊• 如果資料超過欄寬,仍會全部印出

Ex.for (i = 8; i < number; i++) printf("%3d %d\n", i, score[i]);

8 31 9 77 10 82 11 62

寬度 =3 回 printf

19

Precisions

• Format– 設定在句點 (.) 之後

• 意義看各個 data type– 整數:最少印出幾個數字

• 數字太小的話,前面補零– 浮點數:

• %f, %e: 小數點後有幾位數字• %g: significant digits 最多位數

– 字串:最多印出幾個字元

20

Examples

printf("%.3d\n", score[i]);

3010232134

printf("%.3f\n", value[i]);

3.01023.0002.135

printf("%.6s\n", monthName[i]);

JanuarFabruaMarch

21

Examples

printf("%.5e\n", score[i]);

3.40000e-0033.40000e-0053.45678e-005

printf("%.5g\n", score[i]);

0.00343.4e-0053.4568e-005

22

Field Widths and Precisions

• Field width and precision 可同時指定– Ex. %5.3f– field width 或 precision 的值想用變數來指定時,用星號 asterisk (*)

• Example:printf( "%*.*f", 7, 2, 98.736 );

%7.2f

回 printf

23

Flags

• 加在 % 後面• 有些 flags 可以組合使用

Flag Description- (minus sign) 靠左對齊Left-justify the output within the specified field.+ (plus sign) 正數會加正號Display a plus sign preceding positive valuesspace 正數前會加一空格Print a space before a positive value not printed with the +

flag.Prefix 0 to the output value when used with the octal conversion specifier o.Prefix 0x or 0X to the output value when used with the hexadecimal conver sionspecifiers x or X.Force a decimal point for a floating-point number printed with e, E, f, g or Gthat does not contain a fractional part. (Normally the decimal point is onlyprinted if a digit follows it.) For g and G specifiers, trailing zeros are noteliminated.

0 (zero) 數字前空位補零Pad a field with leading zeros.

#

24

Examples

printf("%8s%d\n", monthName[i], i+1);

January1Fabruary2 March3

printf("%-8s%d\n", monthName[i], i+1);

January 1Fabruary2March 3

printf("%-8s%+d\n", monthName[i], i+1);

January +1Fabruary+2March +3

25

Examples

printf("%06d\n", score[i]);000085000100

printf("%d\n", number[i]);85-85

printf("% d\n", number[i]); 85-85

26

Examples

printf("%o, %#o\n", 1487, 1487);2717, 02717

printf("%x, %#x\n", 1487, 1487);5cf, 0x5cf

printf("%X, %#X\n", 1487);5CF, 0X5CF

27

特殊字元Escape sequence Description

\' Output the single quote (') character.

\" Output the double quote (") character.

\? Output the question mark (?) character.

\\ Output the backslash (\) character.

\a Cause an audible (bell) or visual alert. \b Move the cursor back one position on the current line. \f Move the cursor to the start of the next logical page. \n Move the cursor to the beginning of the next line. \r Move the cursor to the beginning of the current line. \t Move the cursor to the next horizontal tab position. \v Move the cursor to the next vertical tab position.

28

scanf()

• scanf(format string, other arguments);

• Format specification:%[*] [width] [{h | l | I64 | L}]type

Ex: scanf( "%3d", &name);

29

Formatting Input with scanfConversion specifier Description

Integers

d Read an optionally signed decimal integer. The corresponding argument is a pointer to integer.

i Read an optionally signed decimal, octal, or hexadecimal integer. The corresponding argument is a pointer to integer.

o Read an octal integer. The corresponding argument is a pointer to unsigned integer.

u Read an unsigned decimal integer. The corresponding argument is a pointer to unsigned integer.

x or X Read a hexadecimal integer. The corresponding argument is a pointer to unsigned integer.

h or l Place before any of the integer conversion specifiers to indicate that a short or long integer is to be input.

Floating-point numbers

e, E, f, g or G Read a floating-point value. The corresponding argument is a pointer to a floating-point variable.

l or L Place before any of the floating-point conversion specifiers to indicate that a double or long double value is to be input.

30

Formatting Input with scanf• Table continued from previous slide

Conversion Specifier Description Characters and strings

c Read a character. The corresponding argument is a pointer to char, no null ('\0') is added.

s Read a string. The corresponding argument is a pointer to an array of type char that is large enough to hold the string and a terminating null ('\0') character—which is automatically added.

Scan set

[scan characters] Scan a string for a set of characters that are stored in an array.

Miscellaneous

p Read an address of the same form produced when an address is output with %p in a printf statement.

n Store the number of characters input so far in this scanf. The corresponding argument is a pointer to integer

% Skip a percent sign (%) in the input. 回

scanf

31

scanf()

scanf("%x",&number);printf("您輸入了 %x,就是 %d\n", number, number);

234afternoon (←自己輸入 )您輸入了 234af,就是 144559

• 讀到不屬於指定型態所用的字元時就會停止

scanf("%d",&number);printf("您輸入了 %d\n", number);234afternoon (←自己輸入 )您輸入了 234

32

Field Width in scanf()

• 最多只讀幾個字元,從中找出資料

33

Examplesscanf("%d", &number);printf("您輸入了 %d\n", number);

123456 (←自己輸入 )您輸入了 123456

• Field width in scanf()Ex. scanf("%2d%d", &a, &b);

printf("您輸入了 %d 和 %d\n", a, b);

123456 (←自己輸入 )您輸入了 12 和 3456

34

Example

scanf("%c%s", &ch, str);printf("您輸入了 %c 和 %s\n", ch, str);

String definition (←自己輸入 )您輸入了 S 和 tring

35

Formatting Input with scanf

• %[ ]: Scan sets– 只讀入在 scan set 裡的字元– 讀到不在 scan set 中的字元時就停止

• %[^ ]: Inverted scan sets– 只讀入不在 scan set 裡的字元– 讀到在 scan set 中的字元時就停止

36

Examples

scanf("%[abcde]",str);printf("您輸入的字串是 %s\n",str);

baby (←自己輸入 )您輸入的字串是 bab

scanf("%[abcde ]",str);printf("您輸入的字串是 %s\n",str);

babe cat (←自己輸入 )您輸入的字串是 babe ca

37

Examples

scanf("%[^abcde]",str);printf("您輸入的字串是 %s\n",str);

lover (←自己輸入 )您輸入的字串是 lov

38

Formatting Input with scanf

• Skipping characters– 所有其他出現在 format specification 中的字元都是在輸入時要被跳過的字元

– 或用 * 來跳過任何字元

39

Example

• scanf("%d/%d/%d", &y, &m, &d);printf("您輸入了 %d年 %d月 %d日 \n",y,m,d);– 必須以此格式輸入99/2/15

– 否則找完第一個數後就因格式不合而結束動作

99/2/15 (←自己輸入 )您輸入了 99年 2月 15日

99-2-15 (←自己輸入 )您輸入了 99年 -858993460 月 -858993460日

40

Example

• scanf("%d/%d/%d",&y,&m,&d);可接受輸入格式99/2/15

• scanf("%d%*c%d%*c%d",&y,&m,&d);可接受輸入格式99/2/1599-2-1599.2&15

__

41

Examples

scanf("%d%*c%d",&m,&d);printf("%d 月 %d 日 \n",m,d);

12_5 (←自己輸入 )12 月 5 日

//跳過任意一個字元

scanf("%d%*d%d",&m,&d);printf("%d 月 %d 日 \n",m,d);

12 23423 5 (←自己輸入 )12 月 5 日

//跳過任意一個整數

42

Examples

scanf("%d%*s%d",&m,&d);printf("%d 月 %d 日 \n",m,d);

12and... 5! (←自己輸入 )12 月 5 日

//跳過任意一個字串

43

Practice

• 輸入格式為 yyyymmdd– 如何讀出年月日?

• 輸入 "Peter is a student"或 "Mary is an operator"– 將第一個字串存入 name ( 名字 ) ,第四個字串存入 occup ( 職業 )

44

22.6 Block I/O

• Reading or writing a block of data into a file at one time.fread()fwrite()

• Especially useful for handling binary files

45

Block I/O

• fread(const void *buffer, size_t size, size_t count, FILE *fptr)– Reading data from a file into a buffer.– count: number of data; size: size of each datum– Ex:

int a[30], k; FILE *fptr; ...// 讀一筆整數資料到一個整數變數fread(&k, sizeof(int), 1, fptr);// 一次讀 30 筆整數資料到一個整數陣列fread(a, sizeof(int), 30, fptr);

46

範例int k; FILE *fptr; ...fread(&k, sizeof(int), 1, fptr);// k 的值就會變成 (00 00 01 02)2=258

// 注意 x86 機器儲存 bytes 的順序是 low byte 在前面, high byte 在後面

02 01 00 00 a1 00 00 0000 00 8C 45 00 77 EF DD.......................

02 01 00 00 a1 00 00 0000 00 8C 45 00 77 EF DD.......................

fptr 所開檔案

47

Block I/O

• fwrite(const void *buffer, size_t size, size_t count, FILE *fptr)– Write data into a file.– count: number of data; size: size of each datum– Ex:int a[30], k; FILE *fptr; ...// 將一個整數變數資料寫到檔案fwrite(&k, sizeof(int), 1, fptr);// 一次將 30 筆陣列中的整數資料寫到檔案fwrite(a, sizeof(int), 30, fptr);

48

22.8 String I/O

• sscanf(char *str, …scanf-params… ) – Same format and usage as scanf(), but its

first parameter is a string and the input comes from this string.

• sprintf(char *str, …printf-params…) – Same format and usage as printf(), but its

first parameter is a character array and the output is stored in the array as a string.

49

22.4 Character I/O

• fgetc(FILE *fptr)– Read in one chatacter from a file.– You should check end of file by yourself by

using feof().– fgetc(stdin) equals getchar()

• fputc(int ch,FILE *fptr)– Write a character into a file.– fputc('a',stdout) equals putchar('a')

50

22.7 File Positioning

• fseek(FILE *fptr, int offset, seek_const )– 將檔案讀取位置移至指定位置

seek_const 可設為• SEEK_SET – 移至檔頭算來 offset 的位置• SEEK_CUR – 移至目前位置再往後 offset 的位置• SEEK_END – 移至檔尾算來 offset 的位置

– offset 單位是 bytes , offset<0 表往回的相對位置• rewind( FILE *fptr )

– 將檔案讀取位置歸零• int ftell( FILE *fptr )

– 傳回目前檔案讀取位置

51

Ex: 取得檔案大小• FILE *fptr = fopen(yourFile,"r");fseek(fptr, 0, SEEK_END);

// 將檔案讀取位置調到檔案結尾處int fsize = ftell(fptr);

// 這時的檔案讀取位置相當於檔案大小rewind(fptr);

// 記得將檔案讀取位置設回開始位置 // 以便從頭讀取