#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main(int argc,char *argv[])
{
int fd;
int i=1;
for(i=1;i<argc;++i)
{
char temp;
fd=open(argv[i],"O_RDWR");
if (fd==-1)
perror("file:");
while (read(fd,&temp,1)!=EOF)
{
putchar(temp);
}
}
}
我执行./a.out a b
。 a
和 b
是我目录中的文件。我收到一条错误消息,提示 File exists
。
open(argv[i],"O_RDWR")
行没有打开文件。
它返回 -1
因为文件存在。那么我应该如何使用 open
系统调用打开文件?
最佳答案
fd=open(argv[i],"O_RDWR"); ^ ^
您传递的是 char *
而不是整数常量。删除 "
,它应该只是:
fd = open(argv[i], O_RDWR);
有趣但可能跑题了,open
一定以为你通过了O_CREAT | O_EXCL
,这就是它提示文件已经存在的原因。
So what i have wriiten is right then???But the code is going into an infinite look printing nothin
read(2)
函数在输入时不返回 EOF
,而是返回 0
。
关于c - 当标志是 char 字符串指针而不是 int 时,open() 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143339/