-1

For one of my homework, I have to read a file (~100 lines). To manipulate the content of the file and extract all the lines, I allocate a buffer with the size of the file with the function stat. And I read the file with the function read with this buffer. I was told that this method was dirty.

Why is it considered to be dirty? I think that if the file is short, it means the size of the char array is acceptable and it means only a few syscall??

bandera
  • 49
  • 9
  • You should ask those that said the method is dirty. – R Sahu Oct 02 '14 at 18:10
  • I should have asked. Now it is too late. – bandera Oct 02 '14 at 18:11
  • I think you should check if the file is a regular file first. The same function ```stat``` can tell you that. Other than that you're safe to check the file size with stat. See the [man](http://pubs.opengroup.org/onlinepubs/000095399/basedefs/sys/stat.h.html) --- ```struct stat. st_size``` --- For regular files, the file size in bytes. For symbolic links, the length in bytes of the pathname contained in the symbolic link. – Sergey M Oct 02 '14 at 18:13
  • 1
    Regarding your size question, [How do you determine the size of a file in C?](http://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c) provides various methods and an analysis of the tradeoffs, which need not be written again--only corrected if there's misinformation there. So I'm marking as duplicate. Regarding copying--if that's your goal--see something like [this question](http://stackoverflow.com/questions/1006797/tried-and-true-simple-file-copying-code-in-c) – HostileFork says dont trust SE Oct 02 '14 at 18:13
  • Another reason it can be considered `"dirty"` is because reading the entire file at one time reads all `end of line characters` into the buffer without translation. (e.g. all `newlines` (and if on DOS/Windows `carriage returns`)). – David C. Rankin Oct 02 '14 at 20:25

1 Answers1

1

If your file is a symbolic link instead of a regular file, you will be getting the "the length in bytes of the pathname contained in the symbolic link." So you shouldn't use it to get the file length. You can see this in the documentation of the struct stat that is returned. (http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html)

Crro
  • 75
  • 1
  • 9