Created
October 26, 2011 18:16
-
-
Save bakerbb/1317222 to your computer and use it in GitHub Desktop.
fstat / malloc / fopen / fread / fclose / free
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <sys/types.h> | |
| #include <sys/stat.h> | |
| #include <fcntl.h> | |
| #include <expat.h> | |
| #include <memory.h> | |
| int main(int argc, char *argv[]) | |
| { | |
| char* szTestFile = "C:/test.txt"; | |
| FILE* pFile; | |
| struct stat sFileStatus; | |
| int nStatus; | |
| int nBufferSize; | |
| char* pBuffer; | |
| int nReturnValue = 0; | |
| memset(&sFileStatus, 0x0, sizeof(struct stat)); | |
| // Status the file size. | |
| if (0 != (nStatus = stat(szTestFile, &sFileStatus))) | |
| { | |
| fprintf(stderr, "stat() failed on file: '%s. Error Code: %d\n", | |
| szTestFile, nStatus); | |
| nReturnValue = -1; | |
| } | |
| // Set the buffer size, Allocate the buffer. | |
| else if(0 == (pBuffer = (char*)malloc(nBufferSize = sFileStatus.st_size))) | |
| { | |
| fprintf(stderr, "buffer allocation failed.\n", | |
| szTestFile); | |
| nReturnValue = -1; | |
| } | |
| // Open the file. | |
| else if(0 == (pFile = fopen(szTestFile, "rb"))) | |
| { | |
| fprintf(stderr, "fopen() failed on file: '%s.\n", | |
| szTestFile); | |
| nReturnValue = -1; | |
| } | |
| // Read the buffer | |
| else if(nBufferSize != (nStatus = fread(pBuffer,1,nBufferSize,pFile))) | |
| { | |
| fprintf(stderr, "fread() failed to read size reported by stat().\n"); | |
| nReturnValue = -1; | |
| } | |
| // Close the file. | |
| if((pFile != 0) && (0 != (nStatus = fclose(pFile)))) | |
| { | |
| fprintf(stderr, "fclose() failed on file: '%s.\n", | |
| szTestFile); | |
| nReturnValue = -1; | |
| } | |
| // Free the buffer. | |
| free (pBuffer); | |
| system("pause"); | |
| return nReturnValue; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment