如何使用write()系统调用向文件描述符写入整数/浮点数?
用
write()系统调用向文件描述符写入整数/浮点数的正确方法 你的代码出现乱码的核心原因:直接用write()写入了整数、浮点数的二进制内存表示,而文本编辑器会把这些二进制字节当作ASCII字符解析,自然会出现乱码。比如int类型的PID是二进制数值,不是"1234"这类可读的ASCII字符串;float的89.2在内存中是浮点编码的二进制数据,也不是"89.2"的ASCII序列。
要实现用write()写入可读的整数/浮点数,必须先把数值转换成人类可读的ASCII字符串,再通过write()写入字节流。以下是具体实现方法:
方法1:借助标准库格式化函数生成字符串
可以用sprintf()将数值格式化为ASCII字符串,再用write()写入文件描述符,这是最便捷的方式:
写入整数示例
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> int main() { int out_fd = open("output.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (out_fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } int pid = getpid(); char buf[20]; // 足够存储int类型的字符串表示 // 将整数格式化为带换行的ASCII字符串 int str_len = sprintf(buf, "%d\n", pid); write(out_fd, buf, str_len); close(out_fd); return 0; }
写入浮点数示例
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> int main() { int out_fd = open("output.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (out_fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } float f = 89.2; char buf[20]; // 将浮点数格式化为保留1位小数的ASCII字符串,带换行 int str_len = sprintf(buf, "%.1f\n", f); write(out_fd, buf, str_len); close(out_fd); return 0; }
方法2:自行实现数值转字符串函数
如果不想依赖sprintf(),可以自己实现数值到ASCII字符串的转换逻辑,比如简易的整数转字符串函数:
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> // 简易正整数转ASCII字符串函数 int int_to_str(int num, char *buf) { int len = 0; // 处理0的特殊情况 if (num == 0) { buf[len++] = '0'; buf[len] = '\0'; return len; } // 先反向存储数字字符 char temp[20]; while (num > 0) { temp[len++] = '0' + (num % 10); num /= 10; } // 反转得到正确顺序的字符串 for (int i = 0; i < len; i++) { buf[i] = temp[len - 1 - i]; } buf[len] = '\0'; return len; } int main() { int out_fd = open("output.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (out_fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } int pid = getpid(); char buf[20]; int num_len = int_to_str(pid, buf); buf[num_len] = '\n'; // 添加换行符 write(out_fd, buf, num_len + 1); close(out_fd); return 0; }
核心总结
write()系统调用仅负责写入原始字节流,不处理任何格式转换。要写入可读的整数/浮点数,必须先将数值转换为ASCII字符串格式,再把字符串的字节写入文件描述符。
内容的提问来源于stack exchange,提问作者Learning
相关产品推荐
相关产品推荐

