It is necessary to allocate memory equal to the file size in bytes, under the array of bytes, and then read the file into this array.

    3 answers 3

    It is necessary to use the fstat function.

    #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main() { void *buffer = NULL; int descriptor = open("filename", O_RDONLY); if (descriptor != -1) { FILE *file = fdopen(descriptor, "rb"); if (file) { struct stat statistics; if (fstat(descriptor, &statistics) != -1) { buffer = (char*)malloc(statistics.st_size); } fclose(file); } close(descriptor); } if (!buffer) { free(buffer); } return 0; } 

      C, C ++

      Or you can do fseek at the end of the file. And then ftell to get the current position of the cursor in the file.

      PS: you need to be careful with files that are larger than max. value for type long. In this case, you can use 64-bit versions of functions.

      PPS: in order for ftell to return exactly the file size, you need to open it in binary mode.

      C ++ (w boost):

       #include <iostream> #include <boost/filesystem.hpp> using namespace boost::filesystem; int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: tut1 path\n"; return 1; } std::cout << argv[1] << " " << file_size(argv[1]) << '\n'; return 0; } 

        Perhaps you should not bathe, but look in the direction of Memory Mapped Files (POSIX) and CreateFileMapping function (WIN)