0

I am trying to do a protocol in c. It has to know the file size to pass it into a protocol which goes between client and server. This is the way I did it.

B32U file_size(FILE * file) {
    assert(file != NULL);
    B32U old = ftell(file);
    fseek(file, 0, SEEK_END);
    B32U size = ftell(file);
    fseek(file,old,SEEK_SET);
    return (size);
}

Does anybody know a better way in order to do that? Since know thans

  • Is not that good? – Lísias de Castro Mar 15 '18 at 10:03
  • 1
    You can use OS dependant function if you doesn't care about portability. Like "stat" for Unix. – Tom's Mar 15 '18 at 10:04
  • those do not work on linux? – Lísias de Castro Mar 15 '18 at 10:05
  • I saw that function. It is really amaizing. Thanks for the sugestion. It gives the complete file reference – Lísias de Castro Mar 15 '18 at 10:08
  • 2
    Also, your function is not really friendly, since it rewind the file descriptor without even care about the original position indicator's stream. You should make a ftell first, then go to end, getting size and going again at the same position at the beginning of the function. – Tom's Mar 15 '18 at 10:12
  • are you saying do a backup from the old position? – Lísias de Castro Mar 15 '18 at 10:21
  • I updated the stuff, see if it is the right way to do the thing? – Lísias de Castro Mar 15 '18 at 10:24
  • Yes, it's better. Personnaly, I would transform the "if (file)" into an assert and say in the doc that the function should take a valid pointer FILE. Also, you don't check if your function call (like fseek, ftell) doesn't fail. So, even if it has 99,9999% probability to succed, when the 0,0001% strike, you will be clueless on what happening. Given that in the worst case scenario you can't move back the position indicator stream at his original position, then you can't salvage your program, but a error detection + log will be helpfull to not waste time chasing a 0,0001% probability error. – Tom's Mar 15 '18 at 10:32

0 Answers0