Moät soá kieán thöùc cô sôû veà laäp trình baèng ngoân ngöõ C

Phaâàn tröôùc | Muïc luïc | Phaâàn sau

XXI. NhaÄp vaø xuaát teäp I

Noäi dung:

 

Teäp vaø stream

Trong C, teäp bieåu thò moät thieát bò cuï theå coù theå trao ñoåi thoâng tin ñöôïc. Noù coù theå laø teäp treân ñóa, maøn aûnh, maùy in, baêng töø. Khi tieáp caän, phaûi coù ñoäng taùc môû teäp; khi khoâng duøng nöõa, ta ñoùng laïi.

Stream laø doøng döõ lieäu (chuoãi byte) chuyeån töø chöông trình ñeán teäp. Khaùc vôùi teäp, stream khoâng phuï thuoäc thieát bò cuï theå. Ñeå thöïc hieän caùc thao taùc I/O, chæ caàn keát hôïp stream vôùi teäp cuï theå.

Stream coù 2 daïng: vaên baûn (text file) vaø nhò phaân (binary file).

Cô sôû veà I/O teäp treân ñóa

Con troû kieåu FILE tham chieáu ñeán moät teäp treân ñóa. Ñònh nghóa:

FILE *fptr;

Trong caáu truùc FILE, coù moät phaàn töû goïi laø ñieåm vò trí (position indicator) chæ vaøo vò trí töùc thôøi cuûa moät teäp maø döõ lieäu coù theå ñoïc hoaëc ghi vaøo. Ta coù theå dòch chuyeån ñieåm ñoù baèng moät soá leänh ñaëc bieät.

fopen(): Môû teäp

#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);

Char *mode chæ caùc mode môû teäp:

"r"

Môû text file ñeå ñoïc

"w"

Taïo text file ñeå vieát

"a"

Môû text file ñeå theâm vaøo

"r+"

Môû text file ñeå ñoïc vaø ghi

"w+"

Taïo text file ñeå vieát hay ñoïc

"a+"

Môû hoaëc taïo text file ñeå theâm vaøo

"rb"

Môû binary file ñeå ñoïc

"wb"

Taïo binary file ñeå vieát

"ab"

Môû binary file ñeå theâm vaøo

"r+b"

Môû binary file ñeå ñoïc vaø ghi

"w+b"

Taïo binary file ñeå vieát hay ñoïc

"a+b"

Môû hoaëc taïo binary file ñeå theâm vaøo

 
Ví duï:
FILE *fptr;
if ((fptr = fopen("test.txt", "r")) == NULL){
   printf("Cannot open test.txt file.\n");
   exit(1);
}

fclose(): Ñoùng teäp

#include <stdio.h>
int fclose(FILE *stream);

stream laø con troû gaén vôùi file ñang môû. Neáu flie ñoùng thaønh coâng, haøm traû laïi 0; neáu khoâng haøm traû laïi EOF.

Ví duï:

1:  /* Opening and closing a file */
2:  #include <stdio.h>
3:
4:  enum {SUCCESS, FAIL};
5:
6:  main(void)
7:  {
8:     FILE *fptr;
9:     char filename[]= "haiku.txt";
10:    int reval = SUCCESS;
11:
12:    if ((fptr = fopen(filename, "r")) == NULL){
13:       printf("Cannot open %s.\n", filename);
14:       reval = FAIL;
15:    } else {
16:       printf("The value of fptr: 0x%p\n", fptr);
17:       printf("Ready to close the file.");
18:       fclose(fptr);
19:    }
20:
21:    return reval;
22: }

Keát quaû:

 
The value of fptr: 0x013E
Ready to close the file.

Ñoïc vaø vieát treân file

fgetc(): Ñoïc moät kyù töï moãi laàn

#include <stdio.h>
int fgetc(FILE *stream);
 

fputc(): Ghi moät kyù töï moãi laàn

#include <stdio.h>
int fputc(int c , FILE *stream);

c laø gía trò nguyeân bieåu thò 1 kyù töï.

Ví duï:

1:  /* Reading and writing one character at a time */
2:  #include <stdio.h>
3:
4:  enum {SUCCESS, FAIL};
5:
6:  void CharReadWrite(FILE *fin, FILE *fout);
7:
8:  main(void)
9:  {
10:    FILE *fptr1, *fptr2;
11:    char filename1[]= "outhaiku.txt";
12:    char filename2[]= "haiku.txt";
13:    int reval = SUCCESS;
14:
15:    if ((fptr1 = fopen(filename1, "w")) == NULL){
16:       printf("Cannot open %s.\n", filename1);
17:       reval = FAIL;
18:    } else if ((fptr2 = fopen(filename2, "r")) == NULL){
19:       printf("Cannot open %s.\n", filename2);
20:       reval = FAIL;
21:    } else {
22:       CharReadWrite(fptr2, fptr1);
23:       fclose(fptr1);
24:       fclose(fptr2);
25:    }
26:
27:    return reval;
28: }
29: /* function definition */
30: void CharReadWrite(FILE *fin, FILE *fout)
31: {
32:    int c;
33:
34:    while ((c=fgetc(fin)) != EOF){
35:       fputc(c, fout);  /* write to a file */
36:       putchar(c);      /* put the character on the screen */
37:    }
38: }

 

Keát quaû:

 
Leading me along
my shadow goes back home
from looking at the moon.
--- Sodo
   (1641-1716)
 
A storm wind blows
out from among the grasses
the full moon grows.
--- Chora
   (1729-1781)

fgets(): Ñoïc moät chuoãi  kyù töïï moãi laàn

#include <stdio.h>
char *fgets(char *s, int n, FILE *stream);
 

fputs(): Ghi moät chuoãi kyù töï moãi laàn

#include <stdio.h>
int fputs(const char *s, FILE *stream);

s tham chieáu ñeán moät maûng kyù töï duøng ñeå löu caùc kyù töï ñoïc ñöôïc, n laø soá phaàn töû cöïc ñaïi cuûa maûng. Neáu ñoïc thaønh coâng, haøm traû laïi con troû cuûa s. Neáu khoâng, haøm traû laïi con troû null, noäi dung maûng khoâng coù gì. fgets() coù theå ñoïc ñeán (n-1) kyù töï vaø theâm vaøo kyù töï \0 neáu khoâng gaëp EOF.  fgets() khaùc gets() ôû ñieåm, neáu gaëp kyù töï sang haøng môùi, fgets() vaãn giöõ kyù töï sang haøng ñoù, nhöng gets(0 seõ thay baèng daáu troáng.

Here s references a character array that is 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 the 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.

Ví duï:

1:  /* Reading and writing one line at a time */
2:  #include <stdio.h>
3:
4:  enum {SUCCESS, FAIL, MAX_LEN = 81};
5:
6:  void LineReadWrite(FILE *fin, FILE *fout);
7:
8:  main(void)
9:  {
10:    FILE *fptr1, *fptr2;
11:    char filename1[]= "outhaiku.txt";
12:    char filename2[]= "haiku.txt";
13:    int reval = SUCCESS;
14:
15:    if ((fptr1 = fopen(filename1, "w")) == NULL){
16:       printf("Cannot open %s for writing.\n", filename1);
17:       reval = FAIL;
18:    } else if ((fptr2 = fopen(filename2, "r")) == NULL){
19:       printf("Cannot open %s for reading.\n", filename2);
20:       reval = FAIL;
21:    } else {
22:       LineReadWrite(fptr2, fptr1);
23:       fclose(fptr1);
24:       fclose(fptr2);
25:    }
26:
27:    return reval;
28: }
29: /* function definition */
30: void LineReadWrite(FILE *fin, FILE *fout)
31: {
32:    char buff[MAX_LEN];
33:
34:    while (fgets(buff, MAX_LEN, fin) != NULL){
35:       fputs(buff, fout);
36:       printf("%s", buff);
37:    }
38: }

 

Keát quaû:

 
Leading me along
my shadow goes back home
from looking at the moon.
--- Sodo
   (1641-1716)
 
A storm wind blows
out from among the grasses
the full moon grows.
--- Chora
   (1729-1781)

fread(): Ñoïc nguyeân moät block döõ lieäu

#include <stdio.h>
size_t fread(void *ptr, size_t size, size_t n, FILE *stream);

ptr laø pointer ñeán moät maûng seõ löu döõ lieäu, size chæ kích thöôùc cuûa moãi maûng, n chæ soá thaønh phaàn seõ ñoïc, stream chæ teäp seõ ñoïc, size_t laø moät kieåu döõ lieäu ñònh nghóa bôûi stdio.h. Haøm seõ traû laïi soá phaàn töû ñoïc ñöôïc, neáu sai seõ traû laïi EOF.

fwrite(): Ghi nguyeân moät block döõ lieäu

#include <stdio.h>
size_t fwrite(const void *ptr, size_t size, size_t n, FILE *stream);

ptr laø pointer ñeán moät maûng seõ löu döõ lieäu, size chæ kích thöôùc cuûa moãi maûng, n chæ soá thaønh phaàn seõ ghi, stream chæ teäp seõ ñoïc, size_t laø moät kieåu döõ lieäu ñònh nghóa bôûi stdio.h. Haøm seõ traû laïi soá phaàn töû ñoïc ñöôïc (n), neáu sai seõ traû soá nhoû hôn n.

feof(): Xaùc ñònh neáu moät teäp ñaõ keát thuùc

#include <stdio.h>
int feof(FILE *stream);

Haøm seõ traû laïi 0 neáu chöa keát thuùc teäp; neáu khaùc, seõ traû laïi soá khaùc 0.

Ví duï:

1:  /* Reading and writing one block at a time */
2:  #include <stdio.h>
3:
4:  enum {SUCCESS, FAIL, MAX_LEN = 80};
5:
6:  void BlockReadWrite(FILE *fin, FILE *fout);
7:  int ErrorMsg(char *str);
8:
9:  main(void)
10: {
11:    FILE *fptr1, *fptr2;
12:    char filename1[]= "outhaiku.txt";
13:    char filename2[]= "haiku.txt";
14:    int reval = SUCCESS;
15:
16:    if ((fptr1 = fopen(filename1, "w")) == NULL){
17:       reval = ErrorMsg(filename1);
18:    } else if ((fptr2 = fopen(filename2, "r")) == NULL){
19:       reval = ErrorMsg(filename2);
20:    } else {
21:       BlockReadWrite(fptr2, fptr1);
22:       fclose(fptr1);
23:       fclose(fptr2);
24:    }
25:
26:    return reval;
27: }
28: /* function definition */
29: void BlockReadWrite(FILE *fin, FILE *fout)
30: {
31:    int num;
32:    char buff[MAX_LEN + 1];
33:
34:    while (!feof(fin)){
35:       num = fread(buff, sizeof(char), MAX_LEN, fin);
36:       buff[num * sizeof(char)] = `\0';  /* append a null character */
37:       printf("%s", buff);
38:       fwrite(buff, sizeof(char), num, fout);
39:    }
40: }
41: /* function definition */
42: int ErrorMsg(char *str)
43: {
44:    printf("Cannot open %s.\n", str);
45:    return FAIL;
46: }

 

Keát quaû:

 
Leading me along
my shadow goes back home
from looking at the moon.
--- Sodo
   (1641-1716)
 
A storm wind blows
out from among the grasses
the full moon grows.
--- Chora
   (1729-1781)

Baøi taäp

  1. Caùc bieåu thöùc sau ñaây laøm gì?
fopen("test.bin", "r+b")
fopen("test.txt" "a")
fopen("test.ini", "w+")
  1. Coù gì sai?
FILE *fptr;
int c;
if ((fptr = fopen("test1.txt", "r")) == NULL){
   while ((c=fgetc(fptr)) != EOF){
      putchar(c);
   }
}
fclose(fptr);
  1. Coù gì sai?
FILE *fptr;
int c;
if ((fptr = fopen("test2.txt", "r")) != NULL){
   while ((c=fgetc(fptr)) != EOF){
      fputc(c, fptr);
   }
   fclose(fptr);
}
  1. Coù gì sai?
FILE *fptr1, *fptr2;
int c;
if ((fptr1 = fopen("test1.txt", "r")) != NULL){
   while ((c=fgetc(fptr1)) != EOF){
      putchar(c);
   }
}
fclose(fptr1);
if ((fptr2 = fopen("test2.txt", "w")) != NULL){
   while ((c=fgetc(fptr1)) != EOF){
      fputc(c, fptr2);
   }
}
fclose(fptr2);
  1. Vieát chöông trình nhaän moät string töø ngöôøi söû duïng vaø löu string ñoù vaøo moät file vôùi teân cuõng do ngöôøi söû duïng cho.

Phaâàn tröôùc | Muïc luïc | Phaâàn sau