请问这个程序出错在哪?

本人是个新手,这个程序很简单,就是创建、写入、读取文件,再读取文件时一直提示错误,打印错误码是bad file descripter貌似文件描述符有问题,请各位老司机看看是什么问题,谢谢

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

int main (void)
{

    char filename[] = "test-3-lseek.txt";                                            //creat file 
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

    int fd = creat(filename, mode);

    if (fd == -1)
    {
        printf ("create file error!\n");
        return 1;
    }

    else printf ("create file OK!\n");




    char buf1[] = "Chaunceyli@test\n";                                              //write file

    int ret = write(fd, buf1, strlen(buf1));

    if (ret == -1)
    {
        printf ("write file error!\n");
        return 2;
    }

    else if (ret == strlen(buf1))
    {
        printf ("write file OK!\n");
//        fsync (fd);                                      
    }

    else 
    {
        printf ("write file partial success!\n");
        return 3;
    }



    off_t offset = 0;
    int whence = SEEK_SET;

    if (lseek (fd, offset, whence) == -1)
    {
        printf ("reset error!\n");
        return 4;
    }

    else printf ("reset OK!\n");



    char buf2[strlen(buf1)] ;                                                               //read file

    ret = read(fd, buf2, strlen(buf1) );

    if (ret == -1)
    {
        printf ("read file error!\n");
        printf ("%d\n",errno);
        return 6;
    }

    else if (ret == strlen(buf1))
    {
        printf ("read file OK!\n");
        printf ("%s", buf2);
    }

    else
    {
        printf ("read file partial success!\n");
        return 7;
    }



    return 0;
}



阅读 2.1k
1 个回答

因为你用错syscall。
http://www.unix.com/man-page/...

The creat() function shall behave as if it is implemented as follows:

int creat(const char *path, mode_t mode) {
    return open(path, O_WRONLY|O_CREAT|O_TRUNC, mode);
}

The creat() function is redundant. Its services are also provided by
the open() function.
It has been included primarily for historical purposes since many existing applications
depend on it.

所以应该把int fd = creat(filename, mode);换成int fd = open(filename, O_RDWR |O_CREAT|O_TRUNC, mode);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进