C language is a powerful programming language widely used in system programming, embedded systems, and other areas. Among them, the write function is one of the essential functions for low-level I/O operations. This article provides a detailed explanation of the write function from basics to advanced usage, helping readers build practical programs.
2. write Function Basics
What is the write function?
write function is a C language system call used to write data via a file descriptor. By using this function, you can send data directly to standard output, files, etc.
It does not depend on the standard library and calls the system call directly.
Flexible Output Destinations
Because it uses file descriptors, you can write data to any file or device, not just standard output.
Differences in Buffering
A major difference between them is the method of data buffering.
printf function: Data is stored in an internal buffer of the standard library and written in bulk when conditions are met (e.g., on newline or when the buffer is full).
Benefit: Improves performance.
Drawback: Data may not appear until the buffer is flushed.
write function: No buffering; data is output immediately each time it is called.
Benefit: Guarantees immediate output.
Drawback: Frequent calls can degrade performance.
Guidelines for Choosing
Condition
Recommended Function
Reason
Formatted output needed
printf
Can format data using format specifiers
Immediate output needed
write
Writes data instantly without buffering
Output to files or devices
write
Can target any file descriptor
Performance‑focused
printf (conditional)
Efficiently buffers for standard output
Comparison with Examples
Using printf:
#include <stdio.h>
int main() {
int value = 42;
printf("Value: %d
", value);
return 0;
}
Both produce the same result, but it is important to understand that their internal processing differs significantly.
5. Applications of the write function in file operations
Opening and Closing Files
To write data to a file, you first need to open the file. Use the open function to open the file, and when the write operation is complete, close the file with the close function. Basic code example:
Check the return value to see how many bytes were actually written.
If an error occurs, use perror to display the error message.
Error Handling and Considerations
When using the write function for file operations, errors can occur. Below are common errors and their remedies.
Unable to open file (open error)
Cause: The file does not exist or insufficient access permissions.
Solution: Verify the correct path and appropriate permissions, and specify O_CREAT if needed.
Write error (write error)
Cause: Insufficient disk space or file system issues.
Solution: Check the error code errno, log it, and identify the cause.
Close error (close error)
Cause: Invalid file descriptor.
Solution: Ensure the file was opened correctly.
Example error‑handling code:
if (write(fd, content, 13) == -1) {
perror("write error");
}
Practical Example of File Operations
An example of writing multiple lines of text to a file is shown. Code example:
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("multiline.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open error");
return 1;
}
const char *lines[] = {"Line 1
", "Line 2
", "Line 3
"};
for (int i = 0; i < 3; i++) {
if (write(fd, lines[i], 7) == -1) {
perror("write error");
close(fd);
return 1;
}
}
close(fd);
return 0;
}
Key points:
Use an array to write multiple lines of data.
Perform error checking inside the loop to ensure safety.
6. Troubleshooting
write function returns -1
Cause:write function returns -1, indicating an error. The following are possible causes.
Invalid file descriptor
Reason: The file is not opened correctly, or it has already been closed.
Solution: Ensure that the file descriptor is valid. c if (fd < 0) { perror("Invalid file descriptor"); return 1; }
Insufficient disk space
Reason: The storage on the device you are trying to write to is insufficient.
Solution: Check the disk space and ensure there is enough free space.
Insufficient access permissions
Reason: The target file or directory does not have the required permissions.
Solution: Change the permissions of the file or directory. bash chmod u+w filename
Some data is not written
Cause: The write function does not guarantee that it will write the specified number of bytes (count). Especially when the file descriptor is a socket or pipe, data may be written only partially. Solution: Track the unwritten portion and handle it in a loop. Example:
Q1: write function when writing strings – what should you watch out for?
A:write function writes data for the specified number of bytes (count) and does not consider that a string is null‑terminated. Therefore, you need to specify the exact size of the data you want to write. Example (incorrect):
const char *message = "Hello, World!";
write(1, message, sizeof(message)); // mistakenly getting the size of the pointer
Q2: How should you handle a negative return value from the write function?
A: If the return value is -1, an error occurred. You can check errno to determine the cause. Typical error codes are shown below.
EACCES: No permission to write to the file.
ENOSPC: No space left on device.
EINTR: Interrupted by a signal.
Example (error handling):
if (write(fd, buffer, size) == -1) {
perror("write error");
// log the error code as needed
}
Q3: What is the difference between the write function and the fwrite function?
A: Both write and fwrite are used to output data, but they differ as follows.
Feature
write function
fwrite function
Level
Low‑level system call
High‑level standard library function
Buffering
No buffering
Buffering provided by the standard library
How the output target is specified
File descriptor
FILE * (stream)
Typical use cases
File systems and sockets
File operations (especially text processing)
Q4: How can you debug when using the write function?
A: You can efficiently debug write issues using the following methods.
strace command
Trace the write system call to inspect the data passed and any errors.
Example: bash strace ./your_program
Log output
Log the content and size of the data being written within the program.
Use GDB (debugger)
Check the buffer contents at write time to verify the data is correct.
Q5: Why does writing to a file sometimes write less data than the intended size?
A: The amount of data the write function writes in a single call depends on the file descriptor and system state. For example, when using sockets or pipes, buffer size limits may cause only part of the data to be written. Solution: Track the unwritten portion and loop calling write.
A: The write function is considered thread‑safe, but if multiple threads operate on the same file descriptor simultaneously, data may become interleaved. Solution:
Use synchronization mechanisms (e.g., mutexes) to prevent race conditions between threads.
8. Summary
In this article, we provided an in‑depth explanation of the C language write function, covering everything from basics to advanced topics, error handling, differences from printf, and troubleshooting. Below we recap the main points.
Importance of the write Function
The write function is a system call that enables low‑level data output and works with various destinations such as files, standard output, and sockets.
It lacks formatting capabilities, but it is extremely useful for immediate output and handling binary data.
fd: File descriptor that specifies the output destination.
buf: Buffer containing the data to be written.
count: Number of bytes to write.
We explored examples of writing to standard output, files, and binary data to learn its flexibility.
Differences from printf
The write call performs low‑level, direct output without buffering.
In contrast, printf provides formatting capabilities and enables higher‑level output operations.
Choosing between them based on the use case is important.
Error Handling and Debugging
When an error occurs in the write function, you can use errno to identify the cause.
We presented ways to handle typical errors such as invalid file descriptors, insufficient disk space, and lack of permissions.
Utilizing strace and debugging tools can streamline troubleshooting.
Troubleshooting and FAQ
We explained how to handle partial writes or interruptions and provided an example implementation for retrying.
The FAQ section comprehensively covered questions related to the write function.
Next Steps
Based on the knowledge of the write function gained in this article, combine it with other C system calls (e.g., read, lseek, close) to create practical programs.
Feel free to tackle more advanced applications such as file manipulation and socket communication.
As your understanding of the write function deepens, you can strengthen the fundamentals of system programming in C. I hope this article helps improve your programming skills. Thank you for reading!