read and write
- C course
- Advanced
- Lesson 5/83
- 5 min
Learn low-level I/O with read and write.
read and write
read(fd, buf, n) reads up to n bytes from a file into buf. The return value is the number of bytes read; 0 at end of file, -1 on error.
write(fd, buf, n) writes n bytes from buf to a file. The return value is the number of bytes written. Both return ssize_t. Important: read may return fewer bytes than requested; this is not an error. For a full read you need a loop.
Buffer and loop
read and write work on a buffer. A buffer is a memory region that temporarily holds data, usually a char array.
You may not read all data in one call. So you call read in a loop, accumulating the bytes read each time. The same applies to write: bytes written may be fewer than requested. High-level fread does this automatically, but at the POSIX level you manage it.
Practice write and byte count
Define const char *msg = "Merhaba\n";. Write to stdout with ssize_t n = write(1, msg, 8);. Then print the byte count with printf("%d\n", (int)n);.
Starter code
#include <stdio.h>
#include <unistd.h>
// Define msg
// Write and assign to n
// Print n
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <unistd.h>
int main(void) {
const char *msg = "Merhaba\n";
ssize_t n = write(1, msg, 8);
printf("%d\n", (int)n);
return 0;
}Expected output
Merhaba 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match I/O concepts
| Term | Meaning |
|---|---|
write |
Sends data |
read |
Receives data |
buffer |
Temporary buffer |
ssize_t |
Signed size type |
2 How does read return the number of bytes read?
- As ssize_t Correct answer
- As void
- As char
- As float
Explanation: read returns ssize_t, a signed integer.
3 read call
char buf[8];
ssize_t n = ____(fd, buf, 7);
char buf[8];
ssize_t n = read(fd, buf, 7);
Explanation: read reads from a descriptor into a buffer.