unix i/o create函数解惑

来源:互联网 发布:外网监控软件 编辑:程序博客网 时间:2024/05/24 05:03
刚开始学习unix编程,在网上看到有人提问代码如下,问题是为什么read的时候总是返回-1.他的理由create的时候已经指定有读写权限了。
#include <stdio.h>#include <fcntl.h>#include <sys/stat.h>#include <stdlib.h>#include <unistd.h>#define FILE_MODE   (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)char    buf1[] = "abcdefghij";char    buf2[] = "ABCDEFGHIJ";char    buf3[10];intmain(void){    int     fd;        if ((fd = creat("/Users/jessy/Desktop/file.hole", FILE_MODE)) < 0)        printf("creat error");        if (write(fd, buf1, 10) != 10)        printf("buf1 write error");    /* offset now = 10 */        printf ("%zd\n", read(fd, buf3, 2));        if (lseek(fd, 16384, SEEK_SET) == -1)        printf("lseek error");    /* offset now = 16384 */        if (write(fd, buf2, 10) != 10)        printf("buf2 write error");    /* offset now = 16394 */    if (lseek(fd, 1, SEEK_SET) != 1)        printf ("Error lseek!\n");    if (read(fd, buf3, 2) < 0) {        perror("read:");    }    printf ("%zd\n", read(fd, buf3, 2));    exit(0);}

下面是create函数的一段话:creat 函数只能以只读方式创建新文件。如果我们要以读写方式创建新文件,可以用 open 函数;creat 函数现在已经没什么用处了,因为 open 比 creat 好用多了。解决!!

perror("read:");可以打印出错误信息。此段代码报Bad file descriptor错误。


0 0