Possible Duplicate:
Easiest way to get file's contents in C
I saw this post but I still feel it involves fseek, ftell etc. And I saw a few other methods where they use feof+fgetc combination but they say feof is not a good option for loop condition. And some other suggest using fgets and reading line by line which I consider as tedious.
Are there any other shorter methods to read entire file contents?
PS: By shorter I mean lines of code.
Either use
mmap()or do it yourself.Omitting error checking, roughly:
This is a readonly copy of the file, allocated at an address of the kernel’s choosing. If you’re on a 32-bit system, you may have to worry about files bigger than 2 GiB. I don’t think you can portably avoid using something like
fstat()to get the file size. If you want to grow the file, you can specify a larger size than the file size, according to the POSIX specification.If you DIY, then the first three lines are the same. Then you use:
As noted before, all error checking was omitted in these examples; don’t risk it in production-ready code.
I went digging for some more nearly production-ready code that uses
mmap()and found:The ‘SQS_xyz’ codes are specific to the program it comes from (as is the function name). This code uses a 3-argument
open()call where a 2-argument version is sufficient.