Linuxシステム呼び出しインタフェース
2372 ワード
open パラメータ解析1.pathname:開くまたは作成するターゲットファイル2.flags:ファイルを開くと複数のパラメータプロセスに転送することができ、以下の定数で「または」演算を行い、flagsを構成する.パラメータ: 戻り値:新しく開いたファイルのディスクリプタの正常な戻りに失敗しました-1 戻りました. open関数では、ターゲットファイルが存在しない場合、open作成が必要な場合、ターゲットファイルが存在しない場合、3番目のパラメータのopenを選択します.3番目のパラメータは、ファイルの作成のデフォルト権限を表します.そうでなければ、2つのパラメータのopenを使用します.
closeパラメータfdは、ファイルを閉じるファイル記述子 である.戻り値:成功して0を返し、失敗して-1 を返します.
write を使用
上記のコードはopenを使用して新しいファイルを開き、新しいファイルにhello taotaoを3行書き込みます.
read を使用
#include
#include
#include
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
O_RDONLY
O_WRONLY
O_RDWR
O_CREAT
O_APPEND
close
#include
int close(int fd);
write
#include
ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
off_t offset);
ssize_t write(int fildes, const void *buf, size_t nbyte);
#include
#include
#include
#include
int main()
{
int fd = open("myfile",O_WRONLY | O_CREAT, 0644);
if(fd < 0)
{
perror("open");
return 1;
}
int count = 3;
const char* buf = "hello taotao
";
while(count--)
{
write(fd,buf,strlen(buf));
}
close(fd);
return 0;
}
上記のコードはopenを使用して新しいファイルを開き、新しいファイルにhello taotaoを3行書き込みます.
read
#include
ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset);
ssize_t read(int fildes, void *buf, size_t nbyte);
#include
#include
#include
#include
#include
#include
#include
int main()
{
int fd = open("myfile",O_RDONLY);
if(fd < 0)
{
perror("open");
exit(1);
}
const char* msg = "hello taotao
";
char buf[1024];
while(1)
{
ssize_t s = read(fd,buf,strlen(msg));
if(s > 0)
{
printf("%s",buf);
}else{
buf[s] = 0;
break;
}
}
close(fd);
}