Exercises : Answer the following Question

Submitted by tushar pramanick on Sun, 03/10/2013 - 22:26

To help solidify your understanding of this lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix E, "Answers to Quiz Questions and Exercises."

    What do the following expressions do?

    fopen("test.bin", "r+b")
    fopen("test.txt" "a")
    fopen("test.ini", "w+")

    What's wrong with the following code segment?

    FILE *fptr;
    int c;
    if ((fptr = fopen("test1.txt", "r")) == NULL){
       while ((c=fgetc(fptr)) != EOF){
          putchar(c);
       }
    }
    fclose(fptr);


    What's wrong with the following code segment?

    FILE *fptr;
    int c;
    if ((fptr = fopen("test2.txt", "r")) != NULL){
       while ((c=fgetc(fptr)) != EOF){
          fputc(c, fptr);
       }
       fclose(fptr);
    }


    What's wrong with the following code segment?

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


Exercises

    Write a program to read the text file haiku.txt and count the number of characters in the file. Also, print out the contents of the file and the total character number on the screen.
    Write a program to receive a string entered by the user, and then save the string into a file with the name also given by the user.
    Given the string "Disk file I/O is tricky.", write a program to write the string into a file called test_21.txt by writing one character at a time. Meanwhile, print out the string on the screen.
    Rewrite exercise 3. This time, try to write one block of characters (that is, one string) at a time.

Comments

Related Items

More Examples of Disk File I/O

More Examples of Disk File I/O

The following sections show several more examples of disk file I/O, such as reading and writing binary data and redirecting the standard streams. Three more I/O functions, fscanf(), fprintf(), and freopen(), are introduced, too.

Random Access to Disk Files

Random Access to Disk Files

Question and Answer

    Q What are the differences between a text stream and a binary stream?

Reading and Writing Disk Files

Reading and Writing Disk Files

The Basics of Disk File I/O

The Basics of Disk File I/O

Now let's focus on how to open and close a disk data file and how to interpret error messages returned by I/O functions.