|< C File I/O 1 | Main | C File I/O 3 >| Site Index | Download |


 

 

 

 

MODULE 9a - MORE C FILE INPUT/OUTPUT 2

-------------------------------------------------------------------------------------

MODULE 19 - C++ FILE I/O

create this, delete that, write this, read that, close this, open that

 

 

 

 

 

 

 

 

 

 

 

 

 

 

My Training Period:        hours

 

The C file input/output abilities for this session:

 

This is a continuation from previous Module. For C++ and MFC (Windows GUI programming) it is called Serialization and the topics are in Single Document Interface (SDI) and Multiple Document Interface (MDI). The C++ standard input/output file is discussed in C++ file input/output. The source code for this Module is: C file input/output program source codes. Trainee must be able to understand and use:

 

          A sequential access file – Read and Write related functions.

          Characters, lines and blocks disk file reading and writing related functions.

          A Random access files – Read and Write related functions.

          Some C File Management Functions.

          Other C libraries used for file I/O.

 

9.6.2    Reading And Writing Disk File

  • The previous program example does not do anything with the tkk1103.txt text file, except open and close it.  Some text has been saved in tkk1103.txt, so how can you read them from the file?

  • In C you can perform I/O operations in the following ways:

  1. Read or write one character at a time.

  2. Read or write one line of text (that is, one line of characters) at a time.

  3. Read or write one block of characters at a time.

9.6.2.1    One Character At A Time

  • Among the C I/O functions, there is a pair of functions, fgetc()/fgetc_s() and fputc()/fputc_s(), that can be used to read from or write to a disk file one character at a time. The _s version is a secure version.

  • The prototype for the fgetc() function is:

int    fgetc(FILE  *stream);

  • The stream is the file pointer that is associated with a stream.  The fgetc() function fetches the next character from the stream specified by stream.  The function then returns the value of an int that is converted from the character.

  • The prototype for the fputc() function is:

int    fputc(int c, FILE *stream);

OPENING, READING, WRITING AND CLOSING FILE

-------------------------------------------

Testing file. This file named testtwo.txt.

After opening files for reading and writing,

without error, content of this file (testtwo.txt)

will be read and output (write) to the other

file named testone.txt and standard

output(screen/console) character by character!!!

 

---HAPPY LEARNING FOLKS!!!----

 

                                            Content of file testtwo.txt

1.          // reading and writing one character at a time

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          // enumerated data type, SUCCESS = 0, FAIL = 1

6.          enum  {SUCCESS, FAIL};

7.           

8.          // prototype function for reading from and writing...

9.          void CharReadWrite(FILE *fin, FILE *fout);

10.        

11.       int main()

12.       {

13.          // declare two file pointers...

14.          FILE *fptr1, *fptr2;

15.          // define the two files name...

16.          char filename1[] = "testone.txt";

17.          char filename2[] = "testtwo.txt";

18.          int reval = SUCCESS;

19.        

20.          // test the opening filename1 for writing....

21.          // if fails...

22.          if ((fptr1 = fopen(filename1, "w")) == NULL)

23.          {

24.               printf("Problem, cannot open %s.\n", filename1);

25.               reval = FAIL;

26.          }

27.          // if opening filename1 for writing is successful,

28.          // test for opening for reading filename2, if fails...

29.          else if ((fptr2 = fopen(filename2, "r")) == NULL)

30.          {

31.               printf("Problem, cannot open %s.\n", filename2);

32.        

33.               reval = FAIL;

34.          }

35.          // if successful opening for reading from filename2

36.          // and writing to filename1...

37.          else

38.          {

39.               // function call for reading and writing...

40.               CharReadWrite(fptr2, fptr1);

41.               // close both files...

42.               if(fclose(fptr1)==0)

43.                printf("%s closed successfully\n", filename1);

44.               if(fclose(fptr2)==0)

45.                printf("%s closed successfully\n", filename2);

46.          }

47.       // for Borland if compiled using its IDE...

48.       // system("pause");

49.       return reval;

50.       }

51.        

52.       // read write function definition

53.       void  CharReadWrite(FILE *fin, FILE *fout)

54.       {

55.          int  c;

56.          // if the end of file is reached, do...

57.          while ((c = fgetc(fin)) != EOF)

58.          {

59.               // write to a file...

60.               fputc(c, fout);

61.               // display on the screen...

62.               putchar(c);

63.          }

64.          printf("\n");

65.       }

 

65 lines: Output:

 

C file I/O open read write and close file stream example

9.6.2.2    One Line At A Time

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

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

OPENING, READING, WRITING one line of characters

----------------------------------------------------

This is file testfour.txt.  This file's content will

be read line by line of characters till no more line

of character found.  Then, it will be output to the

screen and also will be copied to file testhree.txt.

Check the content of testhree.txt file...

----------------------------------------------------

------------------HAVE A NICE DAY-------------------

 

                                                Content of testfour.txt file

 

1.          // reading and writing one line at a time

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          enum  {SUCCESS, FAIL, MAX_LEN = 100};

6.           

7.          // a function prototype for read and writes by line...

8.          void  LineReadWrite(FILE *fin, FILE *fout);

9.           

10.       int main(void)

11.       {

12.           FILE *fptr1, *fptr2;

13.           // file testhree.txt is located at the root, c:

14.           // you can put this file at any location provided

15.           // you provide the full path, same for testfour.txt

16.           char filename1[] = "c:\\testhree.txt";

17.           char  filename2[] = "c:\\testfour.txt";

18.           char  reval = SUCCESS;

19.           

20.           // test opening testhree.txt file for writing, if fail...

21.           if((fptr1 = fopen(filename1,"w")) == NULL)

22.           {

23.                 printf("Problem, cannot open %s for writing.\n", filename1);

24.                 reval = FAIL;

25.           }

26.           

27.           // test opening testfour.txt file for reading, if fail...

28.           else if((fptr2=fopen(filename2, "r"))==NULL)

29.           {

30.                 printf("Problem, cannot open %s for reading.\n", filename2);

31.                 reval = FAIL;

32.           }

33.        

34.           // if opening for writing and reading successful, do...

35.           else

36.           {

37.                 // function call for read and write, line by line...

38.                 LineReadWrite(fptr2, fptr1);

39.                 // close both files stream...

40.                 if(fclose(fptr1)==0)

41.                      printf("%s successfully closed.\n", filename1);

42.                 if(fclose(fptr2)==0)

43.                      printf("%s successfully closed.\n", filename2);

44.               }

45.           // for Borland screenshot

46.           // system("pause");

47.           return reval;

48.       }

49.        

50.       // function definition for line read, write...

51.       void LineReadWrite(FILE *fin, FILE *fout)

52.       {

53.           // local variable...

54.           char buff[MAX_LEN];

55.           while(fgets(buff, MAX_LEN, fin) !=NULL)

56.           {

57.             // write to file...

58.             fputs(buff, fout);

59.             // write to screen...

60.             printf("%s", buff);

61.           }

62.       }

 

62 lines: Output:

 

C file I/O open read write line by line close file stream example

 

  • In this program example, the text files are located in C:\ drive.  The fgets() function is called repeatedly in a while loop to read one line of characters at a time from the testfour.txt file, until it reaches the end of the text file.

  • In line 54, the array name buff and the maximum number of the array elements MAX_LEN are passed to the fgets() function, along with the file pointer fin that is associated with the opened testfour.txt file.

  • Meanwhile, each line read by the fgets() function is written to another opened text file called testhree.txt that is associated with the file pointer fout.  This is done by invoking the fputs() function in line 58.

  • The statement in line 60 prints the contents of each string on the screen so that you see the contents of the testfour.txt file.  You also can view the testhree.txt file content in a text editor to make sure that the contents of the testfour.txt file have been written to the testhree.txt file.

9.6.2.3    One Block At A Time

  • You can also read or write a block of data at a time.  There are two C I/O functions, fread() and fwrite(), that can be used to perform block I/O operations.

  • The prototype for the fread() function is:

 

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

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

int    feof(FILE    *stream);

OPENING, READING AND WRITING ONE BLOCK OF DATA

-----------------------------------------------

This is file testsix.txt. Its content will be

read and then output to the screen/console and

copied to testfive.txt file.  The reading and

writing based on block of data.  May be this

method is faster compared to read/write by

character, by line.....

-----------------------------------------------

------------------END--------------------------

 

                                                Content of testsix.txt file

 

1.          // reading and writing one block at a time

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          // declare enum data type, you will

6.          // learn this in other module...

7.          enum  {SUCCESS, FAIL, MAX_LEN = 80};

8.           

9.          // function prototype for block reading and writing

10.       void  BlockReadWrite(FILE  *fin, FILE  *fout);

11.       // function prototype for error messages...

12.       int   ErrorMsg(char  *str);

13.        

14.       int main(void)

15.       {

16.             FILE  *fptr1, *fptr2;

17.             // define the filenames...

18.             // the files location is at c:\Temp

19.             char  filename1[] = "c:\\Temp\\testfive.txt";

20.             char  filename2[] = "c:\\Temp\\testsix.txt";

21.             int  reval = SUCCESS;

22.           

23.             // test opening testfive.txt file for writing, if fail...

24.             if((fptr1 = fopen(filename1, "w")) == NULL)

25.             {

26.                  reval = ErrorMsg(filename1);

27.             }

28.           

29.             // test opening testsix.txt file for reading, if fail...

30.             else if ((fptr2 = fopen(filename2, "r")) == NULL)

31.             {

32.                  reval = ErrorMsg(filename2);

33.             }

34.             // if opening files for writing and reading is successful, do...

35.             else

36.             {

37.                  // call function for reading and writing

38.                  BlockReadWrite(fptr2, fptr1);

39.                  // close both files streams...

40.                  if(fclose(fptr1)==0)

41.                   printf("%s successfully closed\n", filename1);

42.                  if(fclose(fptr2)==0)

43.                   printf("%s successfully closed\n", filename2);

44.             }

45.             printf("\n");

46.             // for Borland...

47.             // system("pause");

48.             return  reval;

49.       }

50.        

51.       // function definition for block read, write

52.       void   BlockReadWrite(FILE  *fin, FILE  *fout)

53.       {

54.             int   num;

55.             char  buff[MAX_LEN + 1];

56.             // while not end of file for input file, do...

57.             while(!feof(fin))

58.             {

59.                  // reading...

60.                  num = fread(buff, sizeof(char), MAX_LEN, fin);

61.                  //append a null character

62.                  buff[num * sizeof(char)] = '\0';

63.                  printf("%s", buff);

64.                  // writing...

65.                  fwrite(buff, sizeof(char), num, fout);

66.             }

67.       }

68.        

69.       // function definition for error message

70.       int  ErrorMsg(char  *str)

71.       {

72.             // display the error message...

73.             printf("Problem, cannot open %s.\n", str);

74.             return    FAIL;

75.       }

 

75 lines: Output:

 

C file I/O open read write by block close file stream example

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

Further C file i/o reading and digging:

 

  1. The source code for this Module is: C file input/output program source codes.
  2. For C++ and MFC (Windows GUI programming) it is called Serialization and the topics are in Single Document Interface (SDI) and Multiple Document Interface (MDI).
  3. Check the best selling C / C++ books at Amazon.com.
  4. Wide character/Unicode is discussed Character Sets, Unicode & Locale and the implementation using Microsoft C is discussed Windows Users & Groups C programming.
  5. Implementation specific information for Microsoft can be found Microsoft C Run-Time Tutorials and More Win32 Windows C Run-Time programming Tutorials.

 

 

 

 

 

 

 

 

 

|< C File I/O 1 | Main | C File I/O 3 >| Site Index | Download |


C File Input/Output:  Part 1 | Part 2 | Part 3 | Part 4 | Part 5