...
This noncompliant code example attempts to open a binary file in binary mode and use fseek() and ftell() to obtain the file size.
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp;
long file_size;
char *buffer;
fp = fopen("foo.bin", "rb");
if (fp == NULL) {
/* Handle Error */
}
if (fseek(fp, 0 , SEEK_END) != 0) {
/* Handle Error */
}
file_size = ftell(fp);
if (file_size == -1) {
/* Handle Error */
}
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle Error */
}
/* ... */
|
...
This compliant solution uses fstat() to obtain the size of the binary file.
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp;
long file_size;
char *buffer;
struct stat stbuf;
int fd;
fd = open("foo.bin", O_RDONLY);
if (fd == -1) {
/* Handle Error */
}
fp = fdopen(fd, "rb");
if (fp == NULL) {
/* Handle Error */
}
if (fstat(fd, &stbuf) == -1) {
/* Handle Error */
}
file_size = stbuf.st_size;
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle Error */
}
/* ... */
|
...
This noncompliant code example attempts to open a text file in text mode and use fseek() and ftell() to obtain the file size.
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp;
long file_size;
char *buffer;
fp = fopen("foo.txt", "r");
if (fp == NULL) {
/* Handle Error */
}
if (fseek(fp, 0 , SEEK_END) != 0) {
/* Handle Error */
}
file_size = ftell(fp);
if (file_size == -1) {
/* Handle Error */
}
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle Error */
}
/* ... */
|
...
This compliant solution uses fstat() instead to the size of the text file.
| Code Block | ||||
|---|---|---|---|---|
| ||||
FILE *fp;
long file_size;
char *buffer;
struct stat stbuf;
int fd;
fd = open("foo.txt", O_RDONLY);
if (fd == -1) {
/* Handle Error */
}
fp = fdopen(fd, "r");
if (fp == NULL) {
/* Handle Error */
}
if (fstat(fd, &stbuf) == -1) {
/* Handle Error */
}
file_size = stbuf.st_size;
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle Error */
}
/* ... */
|
...