C++ 无法“打开”该文件,但“lseek”已正确完成
我正在处理C++ 无法“打开”该文件,但“lseek”已正确完成,c++,c,unix,C++,C,Unix,我正在处理unix系统调用。 在我的代码中,我想打开文件,并对该文件执行lseek操作。 请查看以下代码 #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> int main(void) { int fd; fd = open("testfile.txt", O_RDONLY); if(fd < 0 ); prin
unix系统调用
。
在我的代码中,我想打开
文件,并对该文件执行lseek
操作。
请查看以下代码
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int fd;
fd = open("testfile.txt", O_RDONLY);
if(fd < 0 );
printf("problem in openning file \n");
if(lseek(fd,0,SEEK_CUR) == -1)
printf("cant seek\n");
else
printf("seek ok\n");
exit(0);
}
我的问题是:
1) 为什么open
系统调用会给我负面的文件描述符?(我已确认testfile.txt文件位于同一目录中)
2) 在这里,我无法打开文件(因为
open()
返回的文件描述符为负数),如果不打开文件,lseek
是如何成功的?事实上,您成功地打开了文件
仅
if(fd<0)
错误,需要删除代码>事实上,您成功地打开了文件
仅if(fd<0)
错误,需要删除代码>大多数API都会告诉您发生错误的原因,对于像open()
这样的系统调用,可以通过查看errno
(并使用strerror()
获取错误的文本版本)来实现。尝试以下操作(删除错误):
#包括
#包括
#包括
#包括
#包括
内部主(空)
{
int-fd;
fd=打开(“testfile.txt”,仅限ordu);
如果(fd<0){//此处删除错误
printf(“打开文件时出现问题:%s\n”,strerror(errno));
返回1;
}
if(lseek(fd,0,SEEK\u CUR)==-1)//您可能想要设置SEEK\u?
printf(“无法搜索:%s\n”,strerror(errno));
其他的
printf(“seek ok\n”);
关闭(fd);
返回0;
}
大多数API都会告诉您发生错误的原因,对于像open()
这样的系统调用,可以通过查看errno
(并使用strerror()
获取错误的文本版本)来实现。尝试以下操作(删除错误):
#包括
#包括
#包括
#包括
#包括
内部主(空)
{
int-fd;
fd=打开(“testfile.txt”,仅限ordu);
如果(fd<0){//此处删除错误
printf(“打开文件时出现问题:%s\n”,strerror(errno));
返回1;
}
if(lseek(fd,0,SEEK\u CUR)==-1)//您可能想要设置SEEK\u?
printf(“无法搜索:%s\n”,strerror(errno));
其他的
printf(“seek ok\n”);
关闭(fd);
返回0;
}
if(fd<0)代码>整个前提是有缺陷的。由于额外的分号而导致错误。您刚才假定文件描述符为负数。如你所见,没有证据的假设是危险的<代码>如果(fd<0)代码>整个前提是有缺陷的。由于额外的分号而导致错误。您刚才假定文件描述符为负数。如你所见,没有证据的假设是危险的您可能知道这一点,但是printf()
withstrerror()
可以通过进行抽象。您可能知道这一点,但是printf()
withstrerror()
可以通过进行抽象。
problem in openning file
seek ok
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
int fd;
fd = open("testfile.txt", O_RDONLY);
if(fd < 0 ) { // Error removed here
printf("problem in opening file: %s\n", strerror(errno));
return 1;
}
if(lseek(fd,0,SEEK_CUR) == -1) // You probably want SEEK_SET?
printf("cant seek: %s\n", strerror(errno));
else
printf("seek ok\n");
close(fd);
return 0;
}