gpt4 book ai didi

c - fcntl 不工作

转载 作者:太空宇宙 更新时间:2023-11-04 04:06:50 25 4
gpt4 key购买 nike

我有一个小程序,它在打开后无法更改文件访问模式。


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<p></p>

<pre><code>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");
}
</code></pre>

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

<pre><code> 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;
</code></pre>

<p>}
</p>

这是我使用文本文件作为输入运行此程序时的输出。

$ 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/

最佳答案

不允许您尝试执行的行为。来自 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.

关于c - fcntl 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5090826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com