- 论坛徽章:
- 0
|
测试代码如下
- #include <stdio.h>
- #include <fcntl.h>
- int main(void)
- {
- char buf[40];
- int fd;
- int i;
- ssize_t nRead;
- if ((fd = open("test.txt", O_RDONLY)) == -1)
- {
- printf("open error");
- exit(0);
- }
-
- if ((nRead = read(fd, (void *)buf, 11)) != 11)
- {
- printf("nRead = %d\n", nRead);
- printf("sorry, read from test.txt error\n");
-
- }
- else
- {
- for(i = 0; i < 11; i++)
- printf("i = %2d, buf[i] = 0x%x\n", i, buf[i]);
- }
- exit(0);
- }
复制代码
只要test.txt文件中的前11个字符中含有换行符,运行结果就是sorry, read from test.txt error
后来我使用dos2unix工具将test.txt文件进行了格式转化,就能正确读取了
没搞明白的是虽然DOS格式下换行符使用 0d 0a两个bytes来表示而UNIX 格式使用0a一个字节来表示
但这不应该会影响read系统调用的返回值吧,没进行格式转化之前,read系统调用应该是读取了11个bytes啊,为什么它会返回10呢 |
|