In: Computer Science
Please just submit text answers for questions a) b) and c)
a) Use the “ls -lt filesize2.c” command to see what the size is reported by OS for this file.
In the file “filesize2.c”, the following code segment was originally commented out:
Uncomment this block of code.
/* fseek(fd, 10L, SEEK_SET);
putc(-1, fd);
rewind(fd); */ //try uncomment this block, to see what it does.
b) Think about what this code segment does.
c) Then compile and run the code with the code segment mentioned in a) uncommented. More specifically, run this program on the text file “filesize2.c” itself by typing (assuming the executable is named “filesize2”); >./filesize2 filesize2.c What is the size of “filesize2.c” that the program reports?
For a), simply write down the size of the file.
For b), simply write down what you think.
For c), simply write down the reported size by the program. Additionally, explain why the sizes reported in a) and c) are different.
//filesize2.c
#include <stdio.h> int main(int argc, char *argv[]){ FILE *fd; char ch; int fileSize=-1; fd = fopen(argv[1], "r+"); /*fseek(fd, 10L, SEEK_SET); putc(-1, fd); rewind(fd); */ //try uncomment this block, to see what it does. do{ ch=getc(fd); fileSize++; // printf("fileSize=%d\n", fileSize); } while( ch != EOF); printf("Size of %s is %d\n", argv[1], fileSize); }
NB:Every file type has a part of memory allocated which defines the type of file and its dependancies. hence the program returns the total length of char as 522 but command prompt returns 534. Hence 12 byte is allocated for filetype identifier.
Solutions:
a)
The file size of c program is (522 + documentation for filetype identifier.) = 534 as displayed after running 'ls -lt filesize2.c'
b)
The program opens the file in read mode, fseek() moves the cursor to 11th char and puts -1 equivalent char. and reset cursor to beginning When the loop runs and char is taken out one by one, at 11th position, the char comes out whose int equivalent is -1. Comparing -1 with EOF, the condition fails as EOF is equivalent to -1 in int. Hence the length is reflected as 10 rather than the actual size of the file.
c)
Size reported by command prompt: (522
+ documentation for filetype identifier.) = 534
Size reported by program: 10
The code segment is part a plays trick and adds an EOF in the
middle of the file which triggers the program to terminate at a
position where there was no EOF initially. Hence program fails to
display actual size of the file.
Hope it helps.