1

に取り組んでい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ずに成功するにはどうすればよいですか?

4

2 に答える 2

6

実際、ファイルを正常に開きます。

ちょうどif(fd < 0 );間違っています、あなたは削除する必要があります;

于 2013-09-04T14:39:29.440 に答える
2

ほとんどの API は、エラーが発生した理由を教えてくれます。そのようなシステム コールの場合は、エラーのテキスト バージョンを参照する(およびエラーのテキスト バージョンを取得するために使用する) ことopen()によって実現されます。以下を試してください(エラーを削除してください):errnostrerror()

#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;

} 
于 2013-09-04T14:43:15.907 に答える