以下代码已编写,用于在 Linux 中使用 sysyem 调用打开文件并将数据写入终端。
要读取文件描述符(fd)的值,它应该分配一个值。正如我们在 if else 语句中知道的那样,从 if 部分 else 部分或 else if 部分一次将执行一个部分。因此,根据以下代码,fd 仅在 else if 行才有值。但是当我传递文件名并运行该程序时,它会打开该文件。文件打开是在 read(() 系统调用的 while 循环中进行的。但是 while 循环在 else 部分中,并且由于文件描述符理论上不能有任何值。那么 read 函数如何准确识别文件?这让我很困惑.
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 10
int main(int argc, char *argv[])
{
int fd,n;
char buff[SIZE];
if(argc != 2)
{
printf("USAGE : %s\n",argv[0] );
exit(1);
}
else if ((fd = open(argv[1],0)) == -1)
{
perror("STATUS");
exit(1);
}
else
{
while((n = read(fd,buff,SIZE)) > 0)
{
write(1,buff,SIZE);
}
close(fd);
}
}
最佳答案
这里发生以下情况:
假设程序是在命令行上使用 xyz.txt 启动的,并且假设 xyz.txt 文件确实存在:
if(argc != 2)
{
// we don't get here because argc == 2
printf("USAGE : %s\n",argv[0] );
exit(1);
}
else if ((fd = open(argv[1],0)) == -1) // the statement in the if clause will therefore
// be executed, fd will be something different
// from -1 because open succeeded
{
perror("STATUS"); // therefore we dont ge here either
exit(1);
}
else
{ // instead we get here and
while((n = read(fd,buff,SIZE)) > 0) // everything works as expected
{
write(1,buff,SIZE);
}
close(fd);
}
关于c - C 中的系统调用(文件描述符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851240/