Programming Language & Its Applications β Virtual Functions and File Handling, NEC licence examination syllabus (Nepal Engineering Council).
Moving characters and bytes with no conversion β get, put, getline, read, write.
>>, because >> silently eats whitespace and converts. It is also how you read a password without echoing it, and how wc and md5sum work. Search "why getline is better than cin >> for strings" β the answer is the first thing that goes wrong when a user types a two-word name.#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
{ std::ofstream f("text.txt");
f << "Nepal Engineering\nCouncil 2026\n"; }
/* 1. get()/put() β a byte-exact copy */
{
std::ifstream in("text.txt");
std::ostringstream out;
int c; /* int, NOT char */
long n = 0;
while ((c = in.get()) != EOF) { out.put(char(c)); n++; }
std::cout << " copied " << n << " chars verbatim\n";
std::cout << " [" << out.str() << "]\n";
}
/* 2. peek() β decide before consuming */
{
std::istringstream s("42abc");
std::cout << " peek sees '" << char(s.peek())
<< "' (not consumed)\n";
int n; s >> n;
std::cout << " then read " << n
<< ", peek now '" << char(s.peek()) << "'\n";
}
/* 3. putback() β un-read a character */
{
std::istringstream s("x123");
char c = char(s.get());
std::cout << " got '" << c << "', not a digit β putting back\n";
s.putback(c);
std::string all; s >> all;
std::cout << " re-read as: " << all << "\n";
}
/* 4. get vs getline on a C array */
{
std::istringstream s("line one\nline two\n");
char buf[32];
s.get(buf, 32);
std::cout << " get -> [" << buf << "] next char is '"
<< (s.peek()=='\n' ? "\\n" : "?") << "'\n";
s.ignore(); /* skip the leftover \n */
s.getline(buf, 32);
std::cout << " getline -> [" << buf << "] newline consumed\n";
}
/* 5. gcount() */
{
std::istringstream s("hello world");
char buf[6];
s.read(buf, 5); buf[5] = '\0';
std::cout << " read 5 -> [" << buf << "] gcount="
<< s.gcount() << "\n";
}
return 0;
}
Output:
copied 31 chars verbatim
[Nepal Engineering
Council 2026
]
peek sees '4' (not consumed)
then read 42, peek now 'a'
got 'x', not a digit β putting back
re-read as: x123
get -> [line one] next char is '\n'
getline -> [line two] newline consumed
read 5 -> [hello] gcount=5
get versus getline difference on character arrays causes a specific, infuriating bug: get(buf,n) in a loop reads the first line, leaves the '
', then reads zero characters on every subsequent call because the delimiter is still there. The loop never advances and never ends. Either use getline, or call ignore() yourself as above.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
/* A buffered copy β how real file utilities work.
4-8 KB is the sweet spot: big enough to amortise syscall
overhead, small enough to stay in L1 cache. */
long bufferedCopy(const std::string &src, const std::string &dst) {
std::ifstream in(src, std::ios::binary);
std::ofstream out(dst, std::ios::binary);
if (!in || !out) return -1;
char buf[4096];
long total = 0;
while (in.read(buf, sizeof buf) || in.gcount() > 0) {
out.write(buf, in.gcount());
total += in.gcount();
}
return total;
}
int main() {
/* make a file with known content */
{
std::ofstream f("big.bin", std::ios::binary);
for (int i = 0; i < 1000; i++) {
int v = i * i;
f.write(reinterpret_cast<const char*>(&v), sizeof v);
}
}
long n = bufferedCopy("big.bin", "big_copy.bin");
std::cout << " copied " << n << " bytes ("
<< n / (long)sizeof(int) << " ints)\n";
/* verify by reading a specific value back */
{
std::ifstream f("big_copy.bin", std::ios::binary);
f.seekg(500 * sizeof(int));
int v; f.read(reinterpret_cast<char*>(&v), sizeof v);
std::cout << " element 500 = " << v
<< " (500^2 = " << 500*500 << ")\n";
}
/* read a whole vector in one call */
{
std::ifstream f("big.bin", std::ios::binary);
std::vector<int> v(1000);
f.read(reinterpret_cast<char*>(v.data()),
v.size() * sizeof(int));
std::cout << " bulk read gcount=" << f.gcount()
<< " v[999]=" << v[999]
<< " (999^2 = " << 999*999 << ")\n";
}
return 0;
}
Output:
copied 4000 bytes (1000 ints)
element 500 = 250000 (500^2 = 250000)
bulk read gcount=4000 v[999]=998001 (999^2 = 998001)
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
int main() {
{ std::ofstream f("sample.txt"); f << "NEC 2026"; }
/* a simple additive checksum β unformatted read is the
only correct way, since every byte counts */
{
std::ifstream f("sample.txt", std::ios::binary);
unsigned long sum = 0; long n = 0;
int c;
while ((c = f.get()) != EOF) { sum += (unsigned char)c; n++; }
std::cout << " " << n << " bytes, checksum = " << sum << "\n";
}
/* hex dump β 8 bytes per line, hex then ASCII */
{
std::ifstream f("sample.txt", std::ios::binary);
char buf[8];
long offset = 0;
while (f.read(buf, 8) || f.gcount() > 0) {
std::streamsize got = f.gcount();
std::cout << " " << std::setw(4) << std::setfill('0')
<< std::hex << offset << " ";
for (int i = 0; i < 8; i++) {
if (i < got)
std::cout << std::setw(2) << std::setfill('0')
<< (int)(unsigned char)buf[i] << ' ';
else std::cout << " ";
}
std::cout << " |";
for (int i = 0; i < got; i++)
std::cout << (buf[i] >= 32 && buf[i] < 127
? buf[i] : '.');
std::cout << "|\n";
offset += got;
}
std::cout << std::dec;
}
return 0;
}
Output:
8 bytes, checksum = 448
0000 4e 45 43 20 32 30 32 36 |NEC 2026|
std::span<std::byte> and std::as_bytes, which give you a type-safe view over raw memory without the reinterpret_cast gymnastics above β std::byte exists precisely because char carries confusing sign and text semantics. C++23 added std::byteswap for the endianness problem. Search "std::byte vs char vs unsigned char"; understanding why the standard needed a fourth byte-like type is a good window into how much history C's char is carrying.cin >> name fails on "Ram Bahadur" and getline does not. State that get() returns int, not char, because of EOF. The get(buf,n) versus getline(buf,n) delimiter difference is a favourite one-mark question. For block I/O, know that read/write take char* and that gcount() is essential for handling the final partial block.Create a free account to tick topics off, take notes as you read, watch the video lessons and get a day-by-day study plan built around your exam date.
Loadingβ¦