当flags是char字符串指针而不是int时,open()函数错误

nup*_*aya 0 c unix

#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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我执行./a.out a b.a并且b是我的目录中的文件.我收到一个错误说File exists.该行open(argv[i],"O_RDWR")未打开该文件.

它返回,-1因为文件存在.那怎么应该使用open系统调用打开文件?

cni*_*tar 5

fd=open(argv[i],"O_RDWR");
                ^      ^
Run Code Online (Sandbox Code Playgroud)

你传递的是一个char *而不是一个整数常量.放下",应该只是:

fd = open(argv[i], O_RDWR);
Run Code Online (Sandbox Code Playgroud)

有趣但可能偏离主题,open一定认为你通过了O_CREAT | O_EXCL,这就是为什么它抱怨已经存在的文件.


那么我所拥有的就是当时的???但是代码进入了无限的印象

该函数read(2)不会返回EOF输入而是返回0.