Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added a second, more canonical example for how to get file sizes on Windows. Identified 32- vs 64-bit portability concerns.

...

This compliant solution uses the Windows _filelength() function to determine the size of the file on a 32-bit OS.  For a 64-bit OS, consider using _filelengthi64 instead.

Code Block
bgColor#CCCCFF
langc
int fd;
long file_size;
char *buffer;

_sopen_s(&fd, "foo.bin", _O_RDONLY, _SH_DENYRW, _S_IREAD);
if (fd == -1) {
  /* Handle error */
}

file_size = _filelength(fd);
if (file_size == -1) {
  /* Handle error */
}

buffer = (char*)malloc(file_size);
if (buffer == NULL) {
  /* Handle error */
}

/* ... */ 

Compliant Solution (Windows)

This compliant solution uses the Windows GetFileSizeEx() function to determine the size of the file on a 32- or 64-bit OS.

Code Block
bgColor#CCCCFF
langc
HANDLE file;
LARGE_INTEGER file_size;
char *buffer;

 
file = CreateFile(TEXT("foo.bin"), GENERIC_READ, 0, NULL, 
                   OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_FILE_HANDLE == file) {
  /* Handle error */
}
 
if (!GetFileSizeEx(file, &file_size)) {
  /* Handle error */
}
 
/* Note: 32-bit portability issue with LARGE_INTEGER truncating to a size_t */
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
  /* Handle error */
}

/* ... */ 

...

Again, this indicates that the return value of ftell() for streams opened in text mode is useful only in calls to fseek() and should not be used for any other purpose.

Compliant Solution (Windows)

The compliant solution used for binary files on Windows can also be used for text files.

...