我有一个小程序,可以在打开后更改文件访问模式。
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/