3

このファイルを作成しました

char *output = "big";
creat(output, O_RDWR);

ファイルを読み込もうとしているとき

 cat big

許可が拒否されています。私のコードの何が問題なのですか? 読み取りおよび書き込み許可モードでファイルを作成する方法は?

ls -l で、big のパーミッションは次のようになりました

----------

これは何を意味するのでしょうか?

4

2 に答える 2

4

モード引数を誤って解釈しました。マニュアルページから:

          mode specifies the permissions to use in case a new file is cre‐
          ated.  This argument must be supplied when O_CREAT is  specified
          in  flags;  if  O_CREAT  is not specified, then mode is ignored.
          The effective permissions are modified by the process's umask in
          the   usual  way:  The  permissions  of  the  created  file  are
          (mode & ~umask).  Note that this mode  only  applies  to  future
          accesses of the newly created file; the open() call that creates
          a read-only file may well return a read/write file descriptor.

そしてまた

   creat()    is    equivalent    to    open()   with   flags   equal   to
   O_CREAT|O_WRONLY|O_TRUNC.

したがって、より適切な呼び出しは次のようになります。

int fd = creat(output, 0644); /*-rw-r--r-- */

O_RDWRただし、開きたい場合は、次を使用してopen()ください。

int fd = open(output, O_CREAT|O_RDWR|O_TRUNC, 0644);
于 2013-02-21T22:17:38.783 に答える
0

これは明らかにパーミッションの問題です。creat が -1 を返さないかどうかを確認してみてください。そうであれば、問題を解決できるように、perror("") を使用して errno 値を出力してください。

私は、これを行うにはむしろ open() を使用したいと思います。なぜなら、creat のマニュアル ページに記載されているように、「open() はデバイス スペシャル ファイルを開くことができますが、creat() はそれらを作成できないことに注意してください。..」および「creat () は、フラグが O_CREAT | O_WRONLY | O_TRUNC" に等しい open() と同等であり、これはパーミッションについては言及していません。

これを行った場合、まったく同じ結果になります。

char*   output = "big";
int     fd;

fd = open(output, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
// do whaterver you want to do in your file
close(fd);

詳しくは「マンツーオープン」

于 2013-02-21T22:15:56.843 に答える