fcntl 不工作
我有一个小程序,在打开文件后会厌倦更改文件访问模式。
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", 曲线);
newval = 曲线 | 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/
I have a small program that tires to change the files access mode after it has been opened.
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;
}
Here is the output when i run this program with a text file as input.
$ 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
Why is the write in the program failing? Also I'm not able to find where the file status flag constants are defined. I checked in usr/include/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试执行的行为是不允许的。从
fcntl(2)
手册页:The behavior you are trying to perform is not allowed. From the
fcntl(2)
man page:如果您阅读 Linux 手册页,您将看到 fcntl 无法更改文件访问模式(例如,从只读更改为读写)。
If you read Linux manpage, you will see that fcntl cannot change file access modes (e.g., from read-only to read-write).