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

标签 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);
        }
    }
}

我执行./a.out a bab 是我目录中的文件。我收到一条错误消息,提示 File existsopen(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/

相关文章:

c - 将 4 个整数同时反向相乘

c - 匹配C样式(单行)注释,并替换为 block 注释(Notepad++中的RegEx)

c - C 中带有 termios : unreliable output capitalization 的串行 I/O

bash - 使用 bash 将数组中的数据添加到文件中的新列

linux - Perl 目录查找器不起作用?

c - 理解 `man ls` 长格式 : set-user-id and set-group-id modes

c++ - 调用头文件中声明的函数

java - 当还必须切换用户时使用 JSch 到 SFTP

linux - 从制表符分隔的文件中提取最后一列

c - 什么时候在 C 语言中使用 ntohs 和 ntohl?