UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

9.6.  Self-assessment questions

Check with these questions that you understand how to use files in C.

  1. There is something wrong with this piece of code. What it is?:

    1    FILE *fptr;
    2    char b = ‘b’;
    3    char *c = &b;
    4    if (fptr = fopen(“file.txt”, “r”))!= NULL) 
    5    {
    6      while(!feof(fptr)) 
    7      {
    8          fwrite(c, sizeof(char),1,fptr)
    9          printf(“Character: %c”,*c);
    10     }
    11     fclose(fptr);
    12   } 
    • Whatever it happens with the file when is open, it has to be closed; therefore, the function call fclose(fptr) in line 11 must be located outside the if statement, after line 11.

    • The first argument in read/write functions (fread/fwrite) is the variable address where the data is going to be read from or write to; therefore, the correct statement in line 8 is fwrite(&c, sizeof(char),1,fptr);

    • The function printf needs the address of the char variable, not its value; therefore, the correct sentence in line 9 is printf(“Character: %c”,c);

    • The program tries to write in a file that has been opened just to be read.

    • Code is correct, there is nothing wrong with it.

  2. You open the file fptr, whose size is 100 bytes. Which of these pairs of sentences is equivalent?

    • rewind(fptr);

         fseek(fptr,-0L, SEEK_END);
    • rewind(fptr);

         fseek(fptr,100L, SEEK_END);
    • rewind(fptr);

         fseek(fptr,0L, SEEK_CUR);
    • rewind(fptr);

         fseek(fptr,-100L, SEEK_SET);
    • All the previous pairs are equivalent.

    • None above.

  3. You open the file fptr. You start reading byte by byte, till the end of file. At that point, which of these sentences is correct?:

    • The file position indicator has remained unchanged at the beginning of the file; it can just be moved with functions rewind or fseek.

    • The file position indicator is located at the end of the file; it has been moving byte by byte, while reading.

    • The file position indicator has remained unchanged at the beginning of the file; it just moves when writing, not when reading.

    • None above.