[英]unable to `open` the file , but `lseek` is done without error
我正在進行unix system calls
。 在我的代碼中,我想open
文件並對該文件執行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);
}
我的輸出是:
problem in openning file
seek ok
我的問題是:
1)為什么open
系統調用會給我負面文件描述符? (我已確認testfile.txt文件位於同一目錄中)
2)在這里我無法打開文件(因為open()
返回否定文件描述符), lseek
如何成功而不打開文件?
實際上,您成功打開了文件。
只是if(fd < 0 );
是錯誤的,您需要刪除;
大多數API會告訴您為什么會發生錯誤,對於通過調用errno
(並使用strerror()
獲取錯誤的文本版本strerror()
實現的系統調用(如open()
)。 請嘗試以下操作(消除了錯誤):
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.