File read using POSIX API's

后端 未结 4 1446
死守一世寂寞
死守一世寂寞 2021-02-03 15:03

Consider the following piece of code for reading the contents of the file into a buffer

#include 
#include 
#include 

        
相关标签:
4条回答
  • 2021-02-03 15:39

    You could consider allocating the buffer dynamically by first creating a buffer of a fixed size using malloc and doubling (with realloc) the size when you fill it up. This would have a good time complexity and space trade off.

    At the moment you repeatedly read into the same buffer. You should increase the point in the buffer after each read otherwise you will overwrite the buffer contents with the next section of the file.

    The code you supply allocates 50 bytes for the buffer yet you pass 4096 as the size to the read. This could result in a buffer overflow for any files over the size of 50 bytes.

    As for the `\n' and '\0'. The newline is probably in the file and the '\0' was just already in the buffer. The buffer is allocated on the stack in your code and if that section of the stack had not been used yet it would probably contain zeros, placed there by the operating system when your program was loaded.

    The operating system makes no attempt to terminate the data read from the file, it might be binary data or in a character set that it doesn't understand. Terminating the string, if needed, is up to you.

    A few other points that are more a matter of style:

    • You could consider using a for (i = 0; buff[i]; ++i) loop instead of a while for the printing out at the end. This way if anyone messes with the index variable i you will be unaffected.
    • You could close the file earlier, after you finish reading from it, to avoid having the file open for an extended period of time (and maybe forgetting to close it if some kind of error happens).
    0 讨论(0)
  • 2021-02-03 15:45

    For your second question, read don't add automatically a character '\0'. If you consider that your file is a textual file, your must add a '\0' after calling read, for indicate the end of string.

    In C, the end of string is represented by this caracter. If read set 4 characters, printf will read these 4 characters, and will test the 5th: if it's not '\0', it will continue to print until next '\0'. It's also a source of buffer overflow

    For the '\n', it is probably in the input file.

    0 讨论(0)
  • 2021-02-03 15:51

    Since you want to read the whole file, the best way is to make the buffer as big as the file size. There's no point in resizing the buffer as you go. That just hurts performance without good reason.

    You can get the file size in several ways. The quick-and-dirty way is to lseek() to the end of the file:

    // Get size.
    off_t size = lseek(fd, 0, SEEK_END); // You should check for an error return in real code
    // Seek back to the beginning.
    lseek(fd, 0, SEEK_SET);
    // Allocate enough to hold the whole contents plus a '\0' char.
    char *buff = malloc(size + 1);
    

    The other way is to get the information using fstat():

    struct stat fileStat;
    fstat(fd, &fileStat); // Don't forget to check for an error return in real code
    // Allocate enough to hold the whole contents plus a '\0' char.
    char *buff = malloc(fileStat.st_size + 1);
    

    To get all the needed types and function prototypes, make sure you include the needed header:

    #include <sys/stat.h> // For fstat()
    #include <unistd.h>   // For lseek()
    

    Note that read() does not automatically terminate the data with \0. You need to do that manually, which is why we allocate an extra character (size+1) for the buffer. The reason why there's already a \0 character there in your case is pure random chance.

    Of course, since buf is now a dynamically allocated array, don't forget to free it again when you don't need it anymore:

    free(buff);
    

    Be aware though, that allocating a buffer that's as large as the file you want to read into it can be dangerous. Imagine if (by mistake or on purpose, doesn't matter) the file is several GB big. For cases like this, it's good to have a maximum allowable size in place. If you don't want any such limitations, however, then you should switch to another method of reading from files: mmap(). With mmap(), you can map parts of a file to memory. That way, it doesn't matter how big the file is, since you can work only on parts of it at a time, keeping memory usage under control.

    0 讨论(0)
  • 2021-02-03 15:58

    1, you can get the file size with stat(filename, &stat), but define the buffer to page size is just fine

    2, first, there is no NULL character after "Hello", it must be accident that the stack area you allocated was 0 before your code executed, please refer to APUE chapter 7.6. In fact you must initialize the local variable before using it.

    I tried to generate the text file with vim, emacs and echo -n Hello > file-to-buff.txt, only vim adds a line break automatically

    0 讨论(0)
提交回复
热议问题