<p>How can I figure out the size of a file, in bytes?</p>

<pre><code>#include &lt;stdio.h&gt;

unsigned int fsize(char* file){
  //what goes here?
}
</code></pre>

[{'answer_id': 8241, 'author': 'Ecton', 'author_id': 457, 'author_profile': 'https://Stackoverflow.com/users/457', 'pm_score': 2, 'selected': False, 'text': "<p>If you're fine with using the std c library:</p>\n\n<pre><code>#include &lt;sys/stat.h&gt;\noff_t fsize(char *file) {\n    struct stat filestat;\n    if (stat(file, &amp;filestat) == 0) {\n        return filestat.st_size;\n    }\n    return 0;\n}\n</code></pre>\n"}, {'answer_id': 8244, 'author': 'PabloG', 'author_id': 394, 'author_profile': 'https://Stackoverflow.com/users/394', 'pm_score': -1, 'selected': False, 'text': "<p>You can open the file, go to 0 offset relative from the bottom of the file with </p>\n\n<pre><code>#define SEEKBOTTOM   2\n\nfseek(handle, 0, SEEKBOTTOM)  \n</code></pre>\n\n<p>the value returned from fseek is the size of the file.</p>\n\n<p>I didn't code in C for a long time, but I think it should work.</p>\n"}, {'answer_id': 8247, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 5, 'selected': False, 'text': '<p>Matt\'s solution should work, except that it\'s C++ instead of C, and the initial tell shouldn\'t be necessary.</p>\n\n<pre><code>unsigned long fsize(char* file)\n{\n    FILE * f = fopen(file, "r");\n    fseek(f, 0, SEEK_END);\n    unsigned long len = (unsigned long)ftell(f);\n    fclose(f);\n    return len;\n}\n</code></pre>\n\n<p>Fixed your brace for you, too.  ;)</p>\n\n<p>Update: This isn\'t really the best solution.  It\'s limited to 4GB files on Windows and it\'s likely slower than just using a platform-specific call like <code>GetFileSizeEx</code> or <code>stat64</code>. </p>\n'}, {'answer_id': 8249, 'author': 'andrewrk', 'author_id': 432, 'author_profile': 'https://Stackoverflow.com/users/432', 'pm_score': 4, 'selected': False, 'text': '<p>**Don\'t do this (<a href="https://www.securecoding.cert.org/confluence/display/c/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file" rel="nofollow noreferrer">why?</a>): </p>\n\n<blockquote>\n  <p>Quoting the C99 standard doc that i found online:  "Setting the file position indicator to end-of-file, as with <code>fseek(file, 0, SEEK_END)</code>, has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.**</p>\n</blockquote>\n\n<p>Change the definition to int so that error messages can be transmitted, and then use <code>fseek()</code> and <code>ftell()</code> to determine the file size.</p>\n\n<pre><code>int fsize(char* file) {\n  int size;\n  FILE* fh;\n\n  fh = fopen(file, "rb"); //binary mode\n  if(fh != NULL){\n    if( fseek(fh, 0, SEEK_END) ){\n      fclose(fh);\n      return -1;\n    }\n\n    size = ftell(fh);\n    fclose(fh);\n    return size;\n  }\n\n  return -1; //error\n}\n</code></pre>\n'}, {'answer_id': 8250, 'author': 'Nickolay', 'author_id': 1026, 'author_profile': 'https://Stackoverflow.com/users/1026', 'pm_score': 2, 'selected': False, 'text': '<p>I found <a href="http://computerprogramming.suite101.com/article.cfm/writing_a_file_size_function" rel="nofollow noreferrer">a method using fseek and ftell</a> and a thread with this question with answers that it can\'t be done in just C in another way.</p>\n<p>You could use a portability library like <a href="https://web.archive.org/web/20131023234554/https://developer.mozilla.org/en-US/docs/NSPR" rel="nofollow noreferrer">NSPR</a> (the library that powers Firefox).</p>\n'}, {'answer_id': 8273, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 6, 'selected': False, 'text': '<p>Don\'t use <code>int</code>. Files over 2 gigabytes in size are common as dirt these days</p>\n\n<p>Don\'t use <code>unsigned int</code>. Files over 4 gigabytes in size are common as some slightly-less-common dirt</p>\n\n<p>IIRC the standard library defines <code>off_t</code> as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.</p>\n\n<p>If you\'re on windows, you should use <a href="http://msdn.microsoft.com/en-us/library/aa364957&#40;VS.85&#41;.aspx" rel="noreferrer">GetFileSizeEx</a> - it actually uses a signed 64 bit integer, so they\'ll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)</p>\n'}, {'answer_id': 8362, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>And if you\'re building a Windows app, use the <a href="http://msdn.microsoft.com/en-us/library/aa364957.aspx" rel="noreferrer">GetFileSizeEx</a> API as CRT file I/O is messy, especially for determining file length, due to peculiarities in file representations on different systems ;)</p>\n'}, {'answer_id': 8384, 'author': 'T Percival', 'author_id': 954, 'author_profile': 'https://Stackoverflow.com/users/954', 'pm_score': 8, 'selected': True, 'text': '<p>On Unix-like systems, you can use POSIX system calls: <a href="https://en.wikipedia.org/wiki/Stat_(system_call)" rel="noreferrer"><code>stat</code> on a path</a>, or <code>fstat</code> on an already-open file descriptor (POSIX <a href="https://man7.org/linux/man-pages/man3/fstat.3p.html" rel="noreferrer">man page</a>, Linux <a href="https://man7.org/linux/man-pages/man2/lstat.2.html" rel="noreferrer">man page</a>).<br />\n(Get a file descriptor from <code>open(2)</code>, or <code>fileno(FILE*)</code> on a stdio stream).</p>\n<p>Based on NilObject\'s code:</p>\n<pre><code>#include &lt;sys/stat.h&gt;\n#include &lt;sys/types.h&gt;\n\noff_t fsize(const char *filename) {\n    struct stat st; \n\n    if (stat(filename, &amp;st) == 0)\n        return st.st_size;\n\n    return -1; \n}\n</code></pre>\n<p>Changes:</p>\n<ul>\n<li>Made the filename argument a <code>const char</code>.</li>\n<li>Corrected the <code>struct stat</code> definition, which was missing the variable name.</li>\n<li>Returns <code>-1</code> on error instead of <code>0</code>, which would be ambiguous for an empty file. <code>off_t</code> is a signed type so this is possible.</li>\n</ul>\n<p>If you want <code>fsize()</code> to print a message on error, you can use this:</p>\n<pre><code>#include &lt;sys/stat.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;errno.h&gt;\n\noff_t fsize(const char *filename) {\n    struct stat st;\n\n    if (stat(filename, &amp;st) == 0)\n        return st.st_size;\n\n    fprintf(stderr, &quot;Cannot determine size of %s: %s\\n&quot;,\n            filename, strerror(errno));\n\n    return -1;\n}\n</code></pre>\n<p>On 32-bit systems you should compile this with the option <code>-D_FILE_OFFSET_BITS=64</code>, otherwise <code>off_t</code> will only hold values up to 2 GB. See the &quot;Using LFS&quot; section of <a href="http://www.suse.de/%7Eaj/linux_lfs.html" rel="noreferrer">Large File Support in Linux</a> for details.</p>\n'}, {'answer_id': 21640919, 'author': 'rco16', 'author_id': 2658421, 'author_profile': 'https://Stackoverflow.com/users/2658421', 'pm_score': 2, 'selected': False, 'text': '<p>I used this set of code to find the file length.</p>\n\n<pre><code>//opens a file with a file descriptor\nFILE * i_file;\ni_file = fopen(source, "r");\n\n//gets a long from the file descriptor for fstat\nlong f_d = fileno(i_file);\nstruct stat buffer;\nfstat(f_d, &amp;buffer);\n\n//stores file size\nlong file_length = buffer.st_size;\nfclose(i_file);\n</code></pre>\n'}, {'answer_id': 37661250, 'author': 'Abdessamad Doughri', 'author_id': 4400861, 'author_profile': 'https://Stackoverflow.com/users/4400861', 'pm_score': -1, 'selected': False, 'text': "<p>Here's a simple and clean function that returns the file size.</p>\n<pre><code>long get_file_size(char *path)\n{\n    FILE *fp;\n    long size = -1;\n    /* Open file for reading */\n    fp = fopen(path, &quot;r&quot;);\n    fseek(fp, 0, SEEK_END);\n    size = ftell(fp); \n    fclose(fp);\n    return size;\n}\n</code></pre>\n"}, {'answer_id': 41387632, 'author': 'adrian', 'author_id': 5487769, 'author_profile': 'https://Stackoverflow.com/users/5487769', 'pm_score': -1, 'selected': False, 'text': "<p>Try this --</p>\n\n<pre><code>fseek(fp, 0, SEEK_END);\nunsigned long int file_size = ftell(fp);\nrewind(fp);\n</code></pre>\n\n<p>What this does is first, seek to the end of the file; then, report where the file pointer is. Lastly (this is optional) it rewinds back to the beginning of the file. Note that <code>fp</code> should be a binary stream. </p>\n\n<p>file_size contains the number of bytes the file contains. Note that since (according to climits.h) the unsigned long type is limited to 4294967295 bytes (4 gigabytes) you'll need to find a different variable type if you're likely to deal with files larger than that.  </p>\n"}, {'answer_id': 54114840, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<h1>POSIX</h1>\n\n<p>The <strong>POSIX</strong> standard has its own method to get file size.\n<br/>\nInclude the <code>sys/stat.h</code> header to use the function.</p>\n\n<h3>Synopsis</h3>\n\n<ul>\n<li>Get file statistics using <a href="https://linux.die.net/man/3/stat" rel="noreferrer"><code>stat(3)</code></a>.</li>\n<li>Obtain the <code>st_size</code> property.</li>\n</ul>\n\n<h3>Examples</h3>\n\n<p><strong>Note</strong>: It limits the size to <code>4GB</code>. If not <code>Fat32</code> filesystem then use the  64bit version!\n</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;sys/stat.h&gt;\n\nint main(int argc, char** argv)\n{\n    struct stat info;\n    stat(argv[1], &amp;info);\n\n    // \'st\' is an acronym of \'stat\'\n    printf("%s: size=%ld\\n", argv[1], info.st_size);\n}\n</code></pre>\n\n<pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;\n#include &lt;sys/stat.h&gt;\n\nint main(int argc, char** argv)\n{\n    struct stat64 info;\n    stat64(argv[1], &amp;info);\n\n    // \'st\' is an acronym of \'stat\'\n    printf("%s: size=%ld\\n", argv[1], info.st_size);\n}\n</code></pre>\n\n<h1>ANSI C (standard)</h1>\n\n<p>The <strong>ANSI C</strong> doesn\'t directly provides the way to determine the length of the file.\n<br/>\nWe\'ll have to use our mind. For now, we\'ll use the seek approach!</p>\n\n<h3>Synopsis</h3>\n\n<ul>\n<li>Seek the file to the end using <a href="https://linux.die.net/man/3/fseek" rel="noreferrer"><code>fseek(3)</code></a>.</li>\n<li>Get the current position using <a href="https://linux.die.net/man/3/ftell" rel="noreferrer"><code>ftell(3)</code></a>.</li>\n</ul>\n\n<h3>Example</h3>\n\n<pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;\n\nint main(int argc, char** argv)\n{\n    FILE* fp = fopen(argv[1]);\n    int f_size;\n\n    fseek(fp, 0, SEEK_END);\n    f_size = ftell(fp);\n    rewind(fp); // to back to start again\n\n    printf("%s: size=%ld", (unsigned long)f_size);\n}\n</code></pre>\n\n<blockquote>\n  <p>If the file is <code>stdin</code> or a pipe. <strong>POSIX, ANSI C</strong> won\'t work.\n  <br/>\n  It will going return <code>0</code> if the file is a pipe or <code>stdin</code>.</p>\n  \n  <p><strong>Opinion</strong>:\n  You should use <strong>POSIX</strong> standard instead. Because, it has 64bit support.</p>\n</blockquote>\n'}, {'answer_id': 56998027, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>I have a function that works well with only <code>stdio.h</code>. I like it a lot and it works very well and is pretty concise:</p>\n\n<pre><code>size_t fsize(FILE *File) {\n    size_t FSZ;\n    fseek(File, 0, 2);\n    FSZ = ftell(File);\n    rewind(File);\n    return FSZ;\n}\n</code></pre>\n'}, {'answer_id': 70643602, 'author': 'BigChief', 'author_id': 539251, 'author_profile': 'https://Stackoverflow.com/users/539251', 'pm_score': 0, 'selected': False, 'text': "<p><strong>C++ MFC</strong> extracted from windows file details, not sure if this is better performing than seek but if it is extracted from metadata I think it is faster because it doesn't need to read the entire file</p>\n<pre><code>ULONGLONG GetFileSizeAtt(const wchar_t *wFile)\n{\n    WIN32_FILE_ATTRIBUTE_DATA fileInfo;\n    ULONGLONG FileSize = 0ULL;\n    //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/nf-fileapi-getfileattributesexa?redirectedfrom=MSDN\n    //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/ns-fileapi-win32_file_attribute_data?redirectedfrom=MSDN\n    if (GetFileAttributesEx(wFile, GetFileExInfoStandard, &amp;fileInfo))\n    {\n        ULARGE_INTEGER ul;\n        ul.HighPart = fileInfo.nFileSizeHigh;\n        ul.LowPart = fileInfo.nFileSizeLow;\n        FileSize = ul.QuadPart;\n    }\n    return FileSize;\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/8236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432/']