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

The if statement

The if statement

If life were a straight line, it would be very boring. The same thing is true for programming. It would be too dull if the statements in your program could only be executed in the order in which they appear.

Mathematical Functions in C

Mathematical Functions in C

Basically, the math functions provided by the C language can be classified into three groups:

    Trigonometric and hyperbolic functions, such as acos(), cos(), and cosh().

Changing Data Sizes

Changing Data Sizes

Enabling or Disabling the Sign Bit

Enabling or Disabling the Sign Bit

As you know, it's very easy to express a negative number in decimal. All you need to do is put a minus sign in front of the absolute value of the number. But how does the computer represent a negative number in the binary format?

Question and Answer

Question and Answer

    Q Which bit can be used as the sign bit in an integer?