سؤال

Here is the code:

#include <stdio.h>
#include <sys/stat.h>
void dump_buffer(void *buffer, off64_t buffer_size)
{
  off64_t i;
  for(i = 0;i < buffer_size; ++i)
  {
     printf("%02x \n", ((unsigned char *)buffer)[i]);
  }
  printf("\n");
}

void ReadFile(std::string fn)
{
    FILE *file;
    file = fopen(fn.c_str(), "rb");
    if (!file)
    {
        fprintf(stderr, "Unable to open file %s", fn.c_str());
        return;
    }
    struct stat64 fsStatBuf;
    stat64(fn.c_str(), &fsStatBuf);
    off64_t fileLen = fsStatBuf.st_size;
    // fseek(file, 0, SEEK_END);
    // fileLen=ftell(file);
    // fseek(file, 0, SEEK_SET);
    unsigned char *buffer;
    buffer=(unsigned char *)malloc(fileLen+1);
    if (!buffer)
    {
        fprintf(stderr, "Memory error!");
                fclose(file);
        return;
    }
    fread(buffer, 1, fileLen, file);
    fclose(file);
    dump_buffer(buffer, fileLen);
    free(buffer);
}

fread reads a file into a block of memory, that is, the heap. Is there a way to read the file into the stack?

هل كانت مفيدة؟

المحلول

Sure - assuming that your stack is large enough to hold fileLen+1 items, you can do this:

unsigned char buffer[fileLen+1];

and skip the call to free() at the end. This works, because C99 allows you to make arrays of variable size. In C++, however, this would not work *. Since most of your program is in C, however, you should be able to use the standard C construct by using a C99 standard-compliant compiler.

Note, however, that unlike malloc that would return NULL on failure, letting you handle the out of memory situation when the file is too large, this way of allocating memory in the automatic area (i.e. on the stack) will crash your program right away.

Also note that since the file is not a C string, you do not need fileLen+1; fileLen would be sufficient to fit the entire file.

* There are compilers that provide a C++ language extension to support variable-length arrays, but the resultant code would not be standard.

نصائح أخرى

I think it would be more portable to have:

unsigned char buffer[MAXFILESIZE];

and then check the filesize before writing, and fail if the file is too large.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top