🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Integer File I/O in C
Learn putw and getw in C, see exactly what lands in the file, and understand why professionals prefer fwrite and fread. Part of our free C tutorial for embedded systems.
Welcome back to this free C programming course. In this lecture we study putw and getw in C, the two classic functions that move one whole integer between your program and a file. They look simple, and that simplicity makes them a perfect doorway into binary file handling, which every engineer doing embedded C programming meets sooner or later, whether it is a calibration table, a firmware settings block or a sensor dump.
We will not just memorise the declarations. We will write the integers, look at the raw bytes in the file, trigger the famous -1 bug on purpose, and then fix it. If you are following this free embedded C course to prepare for interviews, the -1 trap in this lecture is a favourite question.
What You Will Learn
- What putw and getw do and where they are declared.
- How an int is stored inside a binary file, byte by byte.
- Why a loop written as while ((v = getw(fp)) != EOF) can silently lose data.
- How to read integers safely with feof and ferror.
- Why fwrite and fread are the portable replacement.
- Where integer file storage shows up in embedded C programming for real products.
Prerequisites
- You can open and close files with fopen and fclose, including the rb and wb modes (earlier lectures in this chapter).
- You know what EOF means and how to test a return value.
- You have gcc installed on Linux, or any C compiler that ships glibc or a similar libc.
Integer File I/O in C: The Big Picture
So far in this chapter we moved single characters (fputc and fgetc). Characters are one byte, so the library never has to worry about how many bytes a value occupies. An integer is different. On most desktop and embedded Linux targets an int is four bytes, on some small microcontrollers it is two. Integer file I/O in C means the library copies the raw bytes of the int into the file, with no text conversion at all. The number 100 does not become the characters ‘1’, ‘0’, ‘0’. It becomes the four bytes 64 00 00 00.
Text storage versus putw storage of the value 100
putw in C: Writing One Integer
The function writes the word-sized value you give it to the stream. Its prototype in stdio.h is:
int putw(int w, FILE *stream);
The file must be opened in a binary-friendly mode such as “wb”. Our first program stores five sensor-style readings and prints what putw returned for the first call.
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("samples.bin", "wb");
if (fp == NULL) {
perror("fopen");
return 1;
}
for (int v = 100; v <= 500; v += 100) {
int rc = putw(v, fp);
if (v == 100)
printf("putw() returned %d for the first call\n", rc);
if (rc == EOF) {
perror("putw");
fclose(fp);
return 1;
}
}
fclose(fp);
puts("5 integers stored in samples.bin");
return 0;
}
Build and run
$ gcc -Wall -Wextra -o ep_int_write ep_int_write.c
$ ./ep_int_write
putw() returned 0 for the first call
5 integers stored in samples.bin
$ ls -l samples.bin
-rw-r--r-- 1 user user 20 Oct 31 12:57 samples.bin
$ od -An -tx1 samples.bin
64 00 00 00 c8 00 00 00 2c 01 00 00 90 01 00 00
f4 01 00 00
Five integers, four bytes each, twenty bytes total. Read the dump slowly: 0x64 is 100, 0xc8 is 200, 0x012c is 300 stored as 2c 01. The least significant byte comes first because this machine is little-endian, just like an ARM Cortex-M or an x86 laptop.
Do not trust the return value to equal the written integer. Some books say putw returns the integer it wrote. The implementation we tested (glibc) returned 0 on success. Treat the result as a pass or fail flag only: compare it with EOF and nothing else.
getw in C: Reading One Integer Back
int getw(FILE *stream);
getw reads the next sizeof(int) bytes and hands them back as an int. At end of file or on a read error it returns EOF, which is -1. That single design choice causes the best-known bug in this area, so read the next section carefully. First, the safe reader:
#include <stdio.h>
int main(void)
{
FILE *fp = fopen("samples.bin", "rb");
if (fp == NULL) {
perror("fopen");
return 1;
}
for (;;) {
int v = getw(fp);
if (v == EOF && (feof(fp) || ferror(fp)))
break;
printf("%d ", v);
}
printf("\n");
fclose(fp);
return 0;
}
$ ./ep_int_read
100 200 300 400 500
The getw EOF Trap: When -1 Is Real Data
EOF is defined as -1. A file that legitimately stores the integer -1 therefore looks exactly like “end of file” to a careless loop. This is not rare. A temperature of -1 degree, an error code of -1, a sentinel marker: all valid data. Let us create the problem on purpose by writing 10, -1, 30 and reading it two ways.
#include <stdio.h>
static void write_trap_file(void)
{
FILE *fp = fopen("trap.bin", "wb");
if (fp == NULL) {
perror("fopen");
return;
}
putw(10, fp);
putw(-1, fp);
putw(30, fp);
fclose(fp);
}
int main(void)
{
int v;
FILE *fp;
write_trap_file();
/* naive loop: stops at the legitimate value -1 */
fp = fopen("trap.bin", "rb");
if (fp == NULL) { perror("fopen"); return 1; }
printf("naive : ");
while ((v = getw(fp)) != EOF)
printf("%d ", v);
printf("\n");
fclose(fp);
/* safe loop: EOF counts only when feof()/ferror() agree */
fp = fopen("trap.bin", "rb");
if (fp == NULL) { perror("fopen"); return 1; }
printf("safe : ");
for (;;) {
v = getw(fp);
if (v == EOF && (feof(fp) || ferror(fp)))
break;
printf("%d ", v);
}
printf("\n");
fclose(fp);
return 0;
}
$ ./ep_minus_one_trap
naive : 10
safe : 10 -1 30
Naive loop versus safe loop on the data 10, -1, 30
The fix is a two-step question: did getw return -1, and does the stream itself confirm end of file or an error? Only when both are true do we stop. The stream flags are the single source of truth.
A Note on Text Files and Terminators
Old DOS-era compilers treated byte 26 (Ctrl+Z) as the end marker of a text file, so reading integers from a text-mode stream could stop at the value 26. On Linux there is no such marker, yet the lesson stands: putw and getw are meant for binary streams opened with “wb” and “rb”. Never point them at a file you also intend to open in an editor.
The Portable Alternative: fwrite and fread
putw and getw are not part of the ISO C standard library. They are inherited from early Unix, glibc still provides them, and strict-standard compile modes may hide their declarations. For new code, use fwrite and fread. They let you state the element size and count, they report how many items were really transferred, and they work for arrays and structures too.
#include <stdio.h>
#define COUNT 5
int main(void)
{
int out[COUNT] = { 11, -1, 250, 4096, 7 };
int in[COUNT];
FILE *fp = fopen("portable.bin", "wb");
if (fp == NULL) { perror("fopen"); return 1; }
if (fwrite(out, sizeof out[0], COUNT, fp) != COUNT) {
perror("fwrite");
fclose(fp);
return 1;
}
fclose(fp);
fp = fopen("portable.bin", "rb");
if (fp == NULL) { perror("fopen"); return 1; }
size_t got = fread(in, sizeof in[0], COUNT, fp);
fclose(fp);
printf("read back %zu values:", got);
for (size_t i = 0; i < got; i++)
printf(" %d", in[i]);
printf("\n");
return 0;
}
$ ./ep_int_fwrite
read back 5 values: 11 -1 250 4096 7
Notice that -1 survives. fread returns a count, never a data value, so there is no overlap between “data” and “status”.
putw vs fwrite: Quick Comparison
| Feature | putw / getw | fwrite / fread |
|---|---|---|
| In ISO C | No (legacy Unix) | Yes |
| Items per call | One int | Any count of any type |
| Error signalling | EOF, ambiguous with -1 | Item count, unambiguous |
| Works with structs and arrays | No | Yes |
| Recommended for new code | No | Yes |
Real-World Use in Embedded C Programming
- Calibration data: a handful of ADC offsets saved on a Linux gateway board and reloaded at boot.
- Counters: boot counts or packet counters kept in a small binary file so they survive a reset.
- Test fixtures: host-side tools that dump raw integer streams for a signal-processing routine to consume.
Bare-metal microcontrollers rarely have a standard filesystem, but the same ideas return in FAT libraries such as FatFs and in flash-storage drivers, where you will again be moving raw words and worrying about size and byte order.
Common Mistakes and Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Reader stops early, last values missing | -1 stored in the data | Check feof and ferror, or switch to fread |
| File looks like garbage in an editor | Binary data, not text | Inspect with od or a hex viewer |
| File works on laptop but not on target | Different int size or byte order | Use fixed-width types and define the byte order explicitly |
| Implicit declaration warning | Strict -std mode hides putw | Use fwrite, or compile in the default GNU mode |
| Garbage values on read | File opened in “r” instead of “rb”, or wrong file | Match the mode to how the file was written |
Best Practices, Performance and Security
- Always test fopen for NULL before the first write or read.
- Use uint32_t or int16_t from stdint.h when the file format must stay the same across machines.
- Never trust file contents. A file edited by someone else can hold any integer, so validate ranges before using a value as an array index.
- Calling putw in a loop is buffered by stdio, so it is not slow. For larger blocks one fwrite call is still cheaper than many small calls.
- Close the file. Buffered data reaches the disk only after fflush or fclose.
Key Takeaways and Conclusion
Summary
- putw copies the raw bytes of one int into a stream; getw reads them back.
- The file holds binary, not text: 100 becomes 64 00 00 00 on a little-endian machine.
- getw returns EOF (-1) for both “end of file” and “error”, and -1 is also a valid integer.
- Always confirm with feof or ferror, or avoid the problem entirely with fread.
- For portable and modern code, prefer fwrite and fread with fixed-width integer types.
Integer file I/O in C is a small topic, but it teaches three habits that matter for the rest of this free embedded C course: look at the bytes, distrust values that double as status codes, and prefer interfaces whose return value tells the truth. In the next lecture we move from numbers to text and meet fputs, the function that writes a string into a file.
Frequently Asked Questions
What do putw and getw do in C?
putw writes one int as raw bytes into a file, and getw reads the next int from a file. They are declared in stdio.h and work on binary streams.
Why does my getw loop stop in the middle of the file?
The file contains the integer -1, which equals EOF. Test feof(fp) and ferror(fp) before treating -1 as the end, or use fread.
Are putw and getw standard C?
No. They are old Unix functions kept by some libraries such as glibc. The ISO C standard does not define them, so use fwrite and fread for portable code.
Can I open the file in a text editor?
You can, but you will see unreadable symbols, because the file holds raw integer bytes. Use od -An -tx1 filename or a hex editor instead.
How many bytes does each putw call write?
sizeof(int) bytes, usually four on Linux and ARM Cortex-M targets. Our test file with five integers was exactly 20 bytes.
Is binary file I/O useful in embedded systems?
Yes. Embedded Linux boards store calibration data, counters and logs in binary files, and the same size and byte-order thinking applies to flash storage on microcontrollers.
Keep Going With the Free C Course
Next up: writing strings to files with fputs. Every lecture in this free C programming course includes tested code you can build and run today.

1 Comment