我正在try 使用不同的C函数实现echo
命令.通过printf
实现它相当简单:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
while (--argc)
printf(((argc == 1) ? "%s\n" : "%s "), *++argv);
}
这样做效果很好:
$ ./a.out Bring a towel
Bring a towel
但是,当我try 使用write
系统调用实现它时:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
while (--argc) {
write(STDOUT_FILENO, *++argv, strlen(*argv));
write(STDOUT_FILENO, ((argc == 1) ? "\n" : " "), 1);
}
}
它正在打印不正确长度的字符串:
$ ./a.out Bring a towel
Bringa atow t
我判断了strlen(*argv)
和printf
返回的字符串长度,它们似乎正确.我也试过每write
次用fflush(stdout)
次冲洗.为什么我的write
系统调用不能正常工作?