1

ファイルを開いた後にファイルアクセスモードを変更するのにうんざりしている小さなプログラムがあります。


int main(int argc, char* argv[])
{
    int fd;
    char *filename = argv[1];
    char data[1];
    int curval;                         //current flag value
    int newval;                         //new flag value

fd = open(filename, O_RDONLY);

while(read(fd, data, 1)>0)
{
    write(STDOUT_FILENO, data, 1);
}

lseek(fd, 0, SEEK_SET);

if((curval = fcntl(fd, F_GETFL, 0))<0)              
{
    perror("file flag get failed");
}

printf("%d\n", curval); newval = curval | O_WRONLY | O_APPEND; printf("%d\n", newval);

    if(fcntl(fd, F_SETFL, newval)<0)
{
    perror("file flag set failed");
}

if(write(fd, argv[2], strlen(argv[2]))<0)   //appending more data to the file
{
    perror("write failed");
    }

lseek(fd, 0, SEEK_SET);

while(read(fd, data, 1)>0)
{
    write(STDOUT_FILENO, data, 1);
}
close (fd);
return 0;

}

テキストファイルを入力としてこのプログラムを実行したときの出力は次のとおりです。

$ cat input
this is the inital data
$ ./a.out input newdata
this is the inital data
0
1025
write failed: Bad file descriptor
this is the inital data

プログラムへの書き込みが失敗するのはなぜですか? また、ファイル ステータス フラグ定数が定義されている場所を見つけることができません。usr/include/ にチェックインしました

4

2 に答える 2

2

実行しようとしている動作は許可されていません。fcntl(2)マニュアルページから:

   F_SETFL (long)
         Set  the  file status flags to the value specified by arg.  File
         access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags
         (i.e.,  O_CREAT,  O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored.
         On Linux this command can only  change  the  O_APPEND,  O_ASYNC,
         O_DIRECT, O_NOATIME, and O_NONBLOCK flags.
于 2011-02-23T12:31:20.450 に答える
0

Linux のマンページを読むと、fcntl がファイル アクセス モードを変更できないことがわかります (たとえば、読み取り専用から読み取り/書き込み)。

于 2011-02-23T12:23:49.737 に答える