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

Aligning Output

Aligning Output
As you might have noticed in the previous section, all output is right-justified. In other words, by default, all output is placed on the right edge of the field, as long as the field width is longer than the width of the output.

 

Adding the Minimum Field Width

Adding the Minimum Field Width

Converting to Hex Numbers

Converting to Hex Numbers

Revisiting the printf() Function

Revisiting the printf() Function

The printf() function is the first C library function you used in this book to print out messages on the screen. printf() is a very important function in C, so it's worth it to spend more time on it.

 

Another Function for Writing: putchar()

Another Function for Writing: putchar()