C++ std::ftell
Measure how many bytes a saved receipt occupies before attaching it to a message.
A simple example
std::ftell
- Start with A regular file containing ASCII AB
- Do this Measure its length
- Result 2 bytes
Syntax
std::ftell(file)
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 on macOS or Linux with a POSIX shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonCheck a receipt attachment size
An office is preparing receipts for transfer and needs to budget storage. Identify which size the program measures, especially when a receipt is also stored inside a compressed archive.
#include <cstdio>
int main() {
std::FILE *file = std::tmpfile();
if (!file) return 1;
if (std::fputs("milk", file) == EOF) { std::fclose(file); return 1; }
long bytes = std::ftell(file);
if (bytes < 0) { std::fclose(file); return 1; }
std::printf("%ld\n", bytes);
std::fclose(file);
return 0;
}
4
The receipt contains the four ASCII bytes in milk. No newline is written.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Read the size field on the saved file. How many bytes did these ASCII characters occupy without a trailing newline?
What to watch for
tmpfile opens a binary update stream. Immediately after this write the byte position equals the length. A position inside an existing file is not its size.