Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Proper understanding of Understanding the difference between text mode and binary mode is important when using functions that operate on file streams. (See FIO14-C. Understand the difference between text mode and binary mode with file streams for more information.)

Section 7.21.9.2 of the C standard [ISO/IEC 9899:2011] states specifies the following specific behavior for fseek() when opening a binary file in binary mode:

...

Section 7.21.9.4 of the C standard [ISO/IEC 9899:2011] states specifies the following specific behavior for ftell() when opening a text file in text mode:

...

Compliant Solution (Windows)

This compliant solution uses the Windows provides an _fstatfilelength() function , which behaves similarly to POSIX fstat()to determine the size of the file.

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 */
}

/* ... */ 

...

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.

Compliant Solution (POSIX)

...