write a program to find size of a file without traversing it character by character?

will anybody tell me the logic hw to approach it

is there any trick involved

Dani AI

Generated

Short answer: you do not need to read a file byte‑by‑byte. There are two common approaches: seek to the end of a stream (fast, simple for binary files) or ask the filesystem for the file’s metadata (portable and reliable for byte counts).

’s fseek/ftell approach works if you open the file in binary mode; when C I/O performs newline or encoding translations in text mode the position returned can be implementation‑defined, so it may not equal the byte count (see fopen and ftell). Contrary to , there is no literal “EOF” byte at the end of a file — EOF is an I/O condition reported by functions, not a stored character (see EOF).

’s stat idea is the usual POSIX method: stat/fstat provide st_size (logical file size in bytes) — that is the recommended way on Unix-like systems (see stat). ’s warning about huge files is valid: older APIs and the long return of ftell can overflow on 32‑bit builds. Use the 64‑bit variants or compile with large‑file support (or use platform APIs) for files >2 GB (see large‑file support and GetFileSizeEx on Windows).

Extra gotchas: st_size is the logical byte count — sparse files, filesystem compression or network mounts can make disk usage differ from that number (sparse files). If the goal is “number of characters” in human text, bytes != characters for multibyte encodings (you must decode to count characters).

Recommended: for C on POSIX, use stat/fstat to get bytes and enable 64‑bit file support for large files. On Windows, use the Win32 size APIs. For C++ programs, std::filesystem::file_size wraps the platform calls safely. See links below for details:

Recommended Answers

All 6 Replies

Use fseek and ftell functions from <stdio.h>.

Every file ends with an EOF character.Find out what the functions which ArkM has stated does and use the above information and you are done.

are you using *nix?

#include <stdio.h>
#include <sys/stat.h>

int getFileSize(char *filename, long *filesize)
{
   struct stat filestats;              

   if (stat(filename, &filestats) < 0) {
   { 
      perror(filename);
      return 0; 
   } 
   else
      *filesize = filestats.st_size;

   printf(" The size of %s is %ld bytes (%3.1f KB)\n", filename, *filesize, (*filesize / 1024.0) );
   return 1;
}

.

Those C functions may not work with huge files -- files that are larger than 2 gig. In MS-Windows win32 api functions would be needed to get the file size of huge files. I don't know about *nix or MAC

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.