本人是个新手,这个程序很简单,就是创建、写入、读取文件,再读取文件时一直提示错误,打印错误码是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;
}
因为你用错syscall。
看http://www.unix.com/man-page/...
所以应该把
int fd = creat(filename, mode);
换成int fd = open(filename, O_RDWR |O_CREAT|O_TRUNC, mode);