🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →putw and getw in C
Store and load integers in binary files, understand why these legacy functions are risky, and learn the portable replacement.
Not every file holds text. Sensor readings, calibration constants and counters are numbers, and writing them as raw integers is compact and fast. putw and getw are the two classic functions for that job: one writes an int to a file, the other reads it back. This lecture of our free C programming course shows how they work, proves with a hex dump what they store, exposes the -1 trap that makes getw() dangerous in a loop, and teaches the portable replacement used in real embedded C programming.
The source book presents putw() and getw() as ordinary tools. Today they are legacy functions, and a good course must say so. All examples below were compiled and run, and one of them shows a compiler refusing to build them in strict mode.
What You Will Learn
In this free C tutorial you will:
- Write and read integer files with putw and getw.
- Inspect the binary file to see exactly which bytes were stored.
- Explain why a stored value of -1 breaks the naive loop.
- Use
feof()andferror()to read safely. - Replace the pair with
fwrite()andfread()and fixed-width integers. - Recognise portability problems: integer size, byte order and strict-mode builds.
Prerequisites
You need fopen() with binary modes ("wb", "rb"), fclose(), the meaning of EOF, and a feeling for how an integer is stored in memory as bytes. The lectures on end of file and on fgetc() cover the rest.
putw and getw: Syntax
int putw(int w, FILE *stream);
int getw(FILE *stream);
| Function | Does | Returns on success | Returns on failure or end |
|---|---|---|---|
putw | Writes the raw bytes of one int | 0 on glibc (the book says it returns the value written) | EOF |
getw | Reads the next int-sized chunk | The integer read | EOF (-1) at the end or on error |
Notice that getw() returns the integer itself. Where a function returns real data through its return value, there is no spare number left to signal a problem. That design choice is the root of the trap described later.
Writing and Reading Integers: A Complete Example
The program writes the ten values 10, 20, … 100, reports how many bytes the file position reached, then reads the values back. The reading loop already uses the safe pattern: it asks feof() and ferror() after every call rather than trusting the returned number.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("ints.bin", "wb");
if (!fp) {
perror("ints.bin");
return EXIT_FAILURE;
}
for (int v = 10; v <= 100; v += 10) {
if (putw(v, fp) == EOF && ferror(fp)) {
perror("putw");
fclose(fp);
return EXIT_FAILURE;
}
}
printf("sizeof(int) = %zu, file position after 10 values = %ld\n",
sizeof(int), ftell(fp));
fclose(fp);
fp = fopen("ints.bin", "rb");
if (!fp) {
perror("ints.bin");
return EXIT_FAILURE;
}
int v;
printf("values read back:");
while (1) {
v = getw(fp);
if (feof(fp) || ferror(fp))
break;
printf(" %d", v);
}
printf("\n");
fclose(fp);
return 0;
}
gcc -Wall -Wextra -o ep_putw ep_putw.c
./ep_putw
wc -c < ints.bin
od -An -tx1 -w16 ints.bin
sizeof(int) = 4, file position after 10 values = 40
values read back: 10 20 30 40 50 60 70 80 90 100
40
0a 00 00 00 14 00 00 00 1e 00 00 00 28 00 00 00
32 00 00 00 3c 00 00 00 46 00 00 00 50 00 00 00
5a 00 00 00 64 00 00 00
Ten integers of four bytes each give 40 bytes. Look at the first four bytes, 0a 00 00 00. The value ten is 0x0A, and it is stored with the least significant byte first. That ordering is called little-endian and it is what x86 and most ARM systems use.
How the integer 10 is stored on a little-endian machine
Why you cannot open this file in a text editor
The file contains raw bytes, including zero bytes. A text editor shows control characters or nothing sensible. Use od, hexdump or xxd to look at it.
The -1 Trap in putw and getw
The most important thing to learn about putw and getw is what happens when the data contains the number -1. The next program stores 5, -1, 7 and 9, then reads them with two different loops.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const int data[] = { 5, -1, 7, 9 };
FILE *fp = fopen("trap.bin", "wb");
if (!fp)
return EXIT_FAILURE;
for (size_t i = 0; i < sizeof data / sizeof data[0]; i++)
putw(data[i], fp);
fclose(fp);
/* Naive loop: -1 is indistinguishable from EOF */
fp = fopen("trap.bin", "rb");
int v, naive = 0;
printf("naive loop :");
while ((v = getw(fp)) != EOF) {
printf(" %d", v);
naive++;
}
printf(" (%d of 4 values)\n", naive);
fclose(fp);
/* Safe loop: ask feof()/ferror() after each call */
fp = fopen("trap.bin", "rb");
int safe = 0;
printf("feof/ferror :");
for (;;) {
v = getw(fp);
if (feof(fp) || ferror(fp))
break;
printf(" %d", v);
safe++;
}
printf(" (%d of 4 values)\n", safe);
fclose(fp);
return 0;
}
gcc -Wall -Wextra -o ep_trap ep_trap.c
./ep_trap
od -An -tx1 -w16 trap.bin
naive loop : 5 (1 of 4 values)
feof/ferror : 5 -1 7 9 (4 of 4 values)
05 00 00 00 ff ff ff ff 07 00 00 00 09 00 00 00
The naive loop, while ((v = getw(fp)) != EOF), read only the 5 and quit. The file is fine: the hex dump shows all 16 bytes, with ff ff ff ff as the second integer. But -1 is the same number as EOF, so the loop decided the file was finished. Two integers were never read, with no error message. A temperature offset, a signed ADC sample or an error code of -1 could all trigger this in production.
The second loop avoids the problem by never comparing the value. It calls getw(), then asks the stream itself whether the call hit the end or failed. Only the stream flags are trusted. The book hints at this fix in its last paragraph; the program shows it in action.
Why putw and getw Are Legacy Functions
Three separate problems make these functions a poor choice for new code, even when used carefully.
| Problem | Explanation | Evidence |
|---|---|---|
| Not standard C | ISO C does not define them, so strict builds reject them and some embedded C libraries do not provide them | See the compiler message below |
| Ambiguous errors | The return value mixes data and status | The -1 trap above |
| Unspecified file format | The size of int and the byte order depend on the machine | Hex dump showing little-endian layout |
Here is the build message when the first example is compiled in strict ISO mode:
gcc -std=c17 -pedantic-errors -o ep_putw ep_putw.c
ep_putw.c:13:13: error: implicit declaration of function 'putw'; did you mean 'puts'? [-Wimplicit-function-declaration]
ep_putw.c:31:13: error: implicit declaration of function 'getw'; did you mean 'getc'? [-Wimplicit-function-declaration]
With default GNU settings the code builds, because glibc exposes extra functions. In strict mode, the declarations disappear. A project that must compile with several toolchains cannot rely on them.
About ASCII 26
The book warns that getw() stops on a byte with value 26 in text files. That is a DOS and Windows text-mode behaviour, where Ctrl+Z marks the end of text. On Linux no byte value ends a file. The practical rule remains: do not use getw() on text files, because text is not a sequence of raw integers in the first place.
The Portable Replacement: fwrite and fread
Use fixed-width integer types from <stdint.h> so the size is the same on every machine, and use fwrite() and fread(). fread() returns the number of items it actually read, so end of file is unambiguous: a return of zero means nothing was read, no matter what values the file contains.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
/* The portable replacement for putw/getw: fixed-width types + fwrite/fread. */
int main(void)
{
const int32_t data[] = { 5, -1, 7, 9 };
const size_t n = sizeof data / sizeof data[0];
FILE *fp = fopen("fixed.bin", "wb");
if (fp == NULL)
return EXIT_FAILURE;
if (fwrite(data, sizeof data[0], n, fp) != n) {
perror("fwrite");
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
fp = fopen("fixed.bin", "rb");
if (fp == NULL)
return EXIT_FAILURE;
int32_t v;
size_t got = 0;
printf("fread loop :");
while (fread(&v, sizeof v, 1, fp) == 1) {
printf(" %d", v);
got++;
}
printf(" (%zu of %zu values)\n", got, n);
fclose(fp);
return 0;
}
gcc -Wall -Wextra -o ep_fread ep_fread.c
./ep_fread
fread loop : 5 -1 7 9 (4 of 4 values)
| Aspect | putw / getw | fwrite / fread |
|---|---|---|
| Standard C | No | Yes |
| Size of each item | Size of int on that machine | Whatever you choose, for example int32_t |
| End and error reporting | Ambiguous value of -1 | Item count returned |
| Many items in one call | No, one at a time | Yes, a whole array |
| Byte order control | None | None directly, but you can convert before writing |
Even with fwrite(), the bytes are still in the machine’s own byte order. If the file will be shared with a PC tool or another board, document the order and convert values explicitly before writing, for example by storing each integer as four bytes with shifts.
Real-World Uses of putw and getw Ideas in Embedded C Programming
- Calibration storage: a device keeps gain and offset values in a small binary file on its flash file system, loaded at boot.
- Counters and statistics: a gateway saves packet counters on shutdown and reloads them on start.
- Sample capture: an ADC task writes a batch of samples to a file for later analysis on a PC.
- Legacy maintenance: older code bases still contain these calls, and you will meet them when fixing bugs or porting to a new compiler.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Loop condition != EOF with getw | Reading stops at a stored -1 | Check feof() and ferror() |
| Opening the file in text mode on Windows | Newline translation corrupts bytes | Use "wb" and "rb" |
Opening with "w" and then reading | No data, getw fails | Use the matching mode |
Assuming sizeof(int) is 4 | File unreadable on a 16-bit or different target | Use int32_t and a defined format |
Compiling with -std=c17 | Implicit declaration errors | Switch to fwrite() and fread() |
| Ignoring a trailing partial record | Damaged file looks valid | Check file size or store a count |
Best Practices for putw and getw
- Prefer
fwrite()andfread()with fixed-width types in all new code. - If you must read with
getw(), testfeof()andferror()after every call. - Open binary files in binary mode, and close them with a checked
fclose(). - Put a small header at the start of the file with a magic number, a version and a record count.
- Validate every value read from a file before using it as an array index or a size.
Performance and security notes
Writing one integer per call is slower than writing an array with one fwrite(), although stdio buffering softens the difference. For security, treat binary files as untrusted. A count read from a file must be range-checked before you use it to allocate memory or index an array, otherwise a damaged or malicious file can cause an overflow.
Key Takeaways
Remember these points
- putw and getw write and read raw
intvalues in binary files. - They are not standard C and may be missing in strict builds or small libraries.
- A stored -1 looks exactly like
EOFtogetw(); always checkfeof()andferror(). - Integer size and byte order are machine dependent, so such files are not portable by default.
- Use
fwrite()andfread()withint32_tand friends instead. - Never use
getw()on text files.
Conclusion
You wrote integers to a file, looked at the actual bytes, lost data to the -1 ambiguity, and replaced the old pair with fread(), which tells you the truth through an item count. The lesson goes beyond two functions: whenever a function returns real data and a failure marker through the same value, check the stream state instead.
The final lecture of this chapter combines everything into a hands-on logging lab, followed by a quiz and interview questions that revise end of file, closing, the standard streams and character input and output.
Frequently Asked Questions
What do putw and getw do?
putw(w, fp) writes one int to a stream as raw bytes, and getw(fp) reads one int back. They work on binary data, not on text. The file after ten calls with 4-byte integers is 40 bytes long.
Are putw and getw part of standard C?
No. The ISO C standard does not define them. They exist in glibc and some older libraries, but a strict build such as gcc -std=c17 hides their declarations, and small embedded C libraries may omit them.
Why is getw unsafe in a while loop?
It reports both a failure and the end of the file with the value -1, and -1 is also a perfectly valid integer. A file that contains -1 makes the naive loop stop early. Check feof() and ferror() after each call instead.
Does ASCII 26 really stop getw on text files?
That statement comes from DOS and Windows text mode, where byte 26 (Ctrl+Z) could mark the end. On Linux and other POSIX systems no byte value ends a file, so the problem does not occur. The real advice, never use getw on text files, still holds because the data is not integers.
What replaces putw and getw?
Use fwrite() and fread() with fixed-width types from <stdint.h> such as int32_t. fread() returns how many items it read, so the end of the file is unambiguous.
Can I share a putw file between a PC and a microcontroller?
Only with care. The size of int and the byte order may differ between the two. Define the file format in terms of fixed-width types and a stated byte order, and convert explicitly when the machine’s order is different.
What happens if the file size is not a multiple of four bytes?
The final incomplete integer cannot be read, and getw() simply reports end of file. The leftover bytes are silently ignored, so a damaged file can look valid. A size check or a header with a record count catches this.
Finish the File Handling Chapter
Next: a complete ADC logger lab, a quiz on this whole part of the free C programming course, and interview questions on file handling.

2 Comments