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


 

 

 

 

MODULE 9b - MORE ON C FILE I/O 4

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

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 i/o abilities that supposed to be acquired:

 

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:

 

  • Some C File Management Functions.

  • Other C libraries used for file I/O.

 

 

9.8    Redirecting The Standard Streams With freopen()

  • We will discuss how to redirect the standard streams, such as stdin and stdout, to disk files.  We can use freopen() function, which can associate a standard stream with a disk file.
  • The prototype for the freopen() function is:

FILE    *freopen(const  char  *filename, const  char  *mode, FILE  *stream);

  • filename is a char pointer referencing the name of a file that you want to associate with the standard stream represented by stream.

  • mode is another char pointer pointing to a string that defines the way to open a file.  The values that mode can have in freopen() are the same as the mode values in the fopen() function.

  • The freopen() function returns a null pointer if an error occurs.  Otherwise, the function returns the standard stream that has been associated with a disk file identified by filename.

  • Let try a program example.

1.          // redirecting a standard stream

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          enum  {SUCCESS, FAIL, STR_NUM = 6};

6.           

7.          void  StrPrint(char  **str);

8.          int   ErrorMsg(char  *str);

9.           

10.       int main(void)

11.       {

12.            // declare and define a pointer to string...

13.            char   *str[STR_NUM] = {

14.                 "Redirecting a standard stream to the text file.",

15.                 "These 5 lines of text will be redirected",

16.                 "so many things you can do if you understand the",

17.                 "concept, fundamental idea - try this one!",

18.                 "--------------DONE--------------------------"};

19.        

20.            char filename[] = "c:\\Temp\\testnine.txt";

21.            int  reval = SUCCESS;

22.        

23.            StrPrint(str);

24.            // create file if not exist and open for writing...

25.            // if exist, discard the previous content...

26.            if(freopen(filename, "w", stdout) == NULL)

27.            {

28.                 reval = ErrorMsg(filename);

29.            }

30.            else

31.            {

32.                 // call StrPrint() function...

33.                 StrPrint(str);

34.                 // close the standard output...

35.                 fclose(stdout);

36.             }

37.            return reval;

38.       }

39.        

40.       // StrPrint() function definition

41.       void  StrPrint(char  **str)

42.       {

43.            int  i;

44.            for(i=0; i<STR_NUM; i++)

45.                 // to standard output-screen/console...

46.                 printf("%s\n", str[i]);

47.            // system("pause");

48.       }

49.        

50.       // ErrorMsg() function definition

51.       int  ErrorMsg(char  *str)

52.       {

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

54.            return  FAIL;

55.       }

 

55 lines: Output:

 

C file I/O open read write redirect stream example

9.9    File Management Functions

9.9.1    Deleting A File

int    remove(const    char    *filename);

1.          // demonstrates the remove() function

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.              

5.          void main()

6.          {

7.               // declare an array to store file name...

8.               char  filename[80];

9.           

10.            printf("Enter the filename to be deleted:  ");

11.            gets(filename);

12.           

13.            // check any error...

14.            if(remove(filename) == 0)

15.              printf("File %s  has been deleted.\n", filename);

16.            else

17.              fprintf(stderr, "Error deleting file %s.\n", filename);

18.            // system("pause");

19.       }

 

19 lines: Output:

 

C file I/O file management remove delete file folder directory

9.9.2  Renaming A File

int    rename(const    char    *oldname, const    char    *newname);

  1. The file oldname does not exist.

  2. A file with the name newname already exists.

  3. You try to rename to another disk.

1.          // using rename() to change a filename

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          void main()

6.          {

7.              char  oldname[80], newname[80];

8.           

9.              printf("Enter current filename: ");

10.            gets(oldname);

11.            printf("Enter new name for file: ");

12.            gets(newname);

13.           

14.            if(rename(oldname, newname) == 0)

15.            {

16.                 printf("%s has been rename %s.\n", oldname, newname);

17.            }

18.            else

19.            {

20.                 fprintf(stderr, "An error has occurred renaming %s.\n", oldname);

21.            }

22.            // system("pause");

23.       }

 

23 lines: Output:

 

C file I/O file management rename

9.7.2           Copying A File

  1. Open the source file for reading in binary mode, using binary mode ensures that the function can copy all sorts of content, not just texts.

  2. Open the destination file for writing in binary mode.

  3. Read a character from the source file.  When a file is first opened, the pointer is at the start of the file, so there is no need to position the file pointer explicitly.

  4. If the function feof() indicates that you’re reached the end of the source file, you’re done and can close both files and return to the calling program.

  5. If you haven’t reached end-of-file, write the character to the destination file, and then loop back to step 3.

1.          // copying a file

2.          #include <stdio.h>

3.          #include <stdlib.h>

4.           

5.          int  file_copy(char   *oldname, char   *newname);

6.           

7.          void  main()

8.          {

9.              char  source[80], destination[80];

10.           

11.            // get the source and destination names

12.            printf("\nEnter source file: ");

13.            gets(source);

14.            printf("\nEnter destination file: ");

15.            gets(destination);

16.           

17.            if(file_copy(source, destination) == 0)

18.                 puts("Copy operation successful");

19.            else

20.                 fprintf(stderr, "Error during copy operation");

21.            // system("pause");

22.       }

23.        

24.       int  file_copy(char *oldname, char  *newname)

25.       {

26.            FILE  *fold, *fnew;

27.            int  c;

28.        

29.            // open the source file for reading in binary mode

30.            if((fold = fopen(oldname, "rb")) == NULL)

31.                return  -1;

32.            // open the destination file for writing in binary mode

33.            if((fnew = fopen(newname, "wb" )) == NULL)

34.            {

35.                 fclose(fold);

36.                 return  -1;

37.            }

38.           

39.            // read one byte at a time from the source, if end of file

40.            // has not been reached, write the byte to the destination

41.            while(1)

42.            {

43.                 c  =  fgetc(fold);

44.                

45.                 if(!feof(fold))

46.                       fputc(c, fnew);

47.                 else

48.                       break;

49.            }

50.            fclose(fnew);

51.            fclose(fold);

52.            return  0;

53.       }

 

     53 lines: Output:

C file I/O file management copy file

 

  • The file_copy() function let you copy anything from a small text file to a huge program file.  But for this program, if the destination file already exists, the function overwrites it without asking.

  • Lines 24 through 37 create a copy function.  Line 30 open the source file, pointed by fold pointer, in binary read mode.

  • Line 33 open the destination file, pointed by fnew pointer, in binary write mode.  Line 35 closes the source file if there is an error opening the destination file.  The while loop does the actual copying of the file.  Line 43 gets a character from the source file, pointed by fold pointer assign to the variable c.

  • Line 45 tests to see whether the end-of-line marker was read.  If the end of the file has been reached, a break statement is executed in order to get out of the while loop in line 48.

  • If the end of the file has not been reached, the character is written to the destination file, pointed by fnew pointer in line 46.

  • For your information the C++ file I/O is discussed in Module 19.

  • The following is a previous C program example, read and write files under the current working directory using gcc.  Create 2 files named testhree.txt and testfour.txt under the current working directory and save some texts in the testfour.txt.

/***************readline.c************

/* reading and writing one line at a time*/

#include <stdio.h>

#include <stdlib.h>

 

enum  {SUCCESS, FAIL, MAX_LEN = 100};

 

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

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

 

int main(void)

{

    FILE *fptr1, *fptr2;

    /* file testhree.txt is located at current directory.

      you can put this file at any location provided

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

    

    char filename1[ ] = "testhree.txt";

    char filename2[ ] = "testfour.txt";

    char reval = SUCCESS;

    

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

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

    {

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

        reval = FAIL;

    }

    

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

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

    {

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

        reval = FAIL;

    }

   

    /* if opening fro writing and reading successful, do... */

    else

    {

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

        LineReadWrite(fptr2, fptr1);

        /* close both files stream... */

        if(fclose(fptr1)==0)

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

        if(fclose(fptr2)==0)

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

    }

    return reval;

   }

 

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

    void LineReadWrite(FILE *fin, FILE *fout)

    {

        /* local variable... */

        char buff[MAX_LEN];

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

        {

                /* write to file... */

                fputs(buff, fout);

                /* write to screen... */

                printf("%s", buff);

        }

}

 

[bodo@bakawali ~]$ gcc readline.c -o readline

[bodo@bakawali ~]$ ./readline

 

------------------LINUX LOR!------------------------

------------FEDORA 3, gcc x.x.x--------------------

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

 

testhree.txt successfully closed.

testfour.txt successfully closed.

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

Related C file i/o reading and digging:

 

  1. 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).
  2. Check the best selling C / C++ books at Amazon.com.
  3. The source code for this Module is: C file input/output program source codes.
  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 3 | Main | C File I/O 5 >| Site Index | Download |


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