|
发表于 2008-3-7 12:56:12
|
显示全部楼层
write() 后要是想直接读刚才的内容的话要先 lseek(fd, 0, SEEK_SET);
至于乱码则是由于缺少字符串结尾的 0, 打印时内存越界了. 给楼主改了一下, 供参考
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <string.h>
- char str[]="Hello China ! ";
- int main(void)
- {
- int fd, n;
- char buf[256];
- if ((fd = open("aa", O_RDWR|O_CREAT|O_TRUNC, 0666)) == -1) {
- printf("open file error.\n");
- exit(-1);
- }
- if (write(fd, str, strlen(str)) == strlen(str)) {
- printf("write success!\n");
- printf("write_fd=%d\n", fd);
- lseek(fd, 0, SEEK_SET);
- if ((n=read(fd, buf, sizeof(str))) != -1) {
- buf[n] = 0;
- printf("read %d \n", n);
- printf("The file: %s\n", buf );
- }
- } else {
- printf("write file error. \n");
- exit(-1);
- }
- close(fd);
- exit(0);
- }
复制代码 |
|