open()调用路径错误

时间:2013-11-15 00:24:51

标签: c file-io system call

我遇到打开输入的问题如果我的第一个参数是路径,我得到这个输出:

  

错误打开:没有这样的文件或目录

但是如果它的文件名没有错误,怎么能解决它?代码如下:

#include<sys/types.h>   //Primitive system data types for abstraction of implementation-dependent data types.
                        //POSIX Standard: 2.6 Primitive System Data Types <sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>

char buf1[]="abcdefghij";
char buf2[]="ABCDEFGHIJ";

int main(int argc, char *argv[])
{
int fd;
if( (fd=open(argv[1],O_CREAT|O_TRUNC|O_WRONLY,S_IRUSR|S_IWUSR))<0) {
    printf("\nError %d en open",errno);
    perror("\nError en open");
    exit(-1);
}
if(write(fd,buf1,10) != 10) {
    perror("\nError en primer write");
    exit(-1);
}

if(lseek(fd,40,SEEK_SET) < 0) {
    perror("\nError en lseek");
    exit(-1);
}

if(write(fd,buf2,10) != 10) {
    perror("\nError en segundo write");
    exit(-1);
}

return 0;
}

测试顺序是:

root@ubuntu:/home/pablo/...# ./tarea1 /home/pablo/hello > temp ; cat temp
root@ubuntu:/home/pablo/...# ./tarea1 /home/pablo/>hello ; cat hello 
Error en open: Is a directory 

2 个答案:

答案 0 :(得分:0)

您的第二个测试序列是:

# ./tarea1 /home/pablo/>hello

这可以更清楚地写成:

# ./tarea1 /home/pablo/ >hello

shell为您的程序提供目录名/home/pablo/,并在当前目录中创建文件hello。程序的任何标准输出都会转到该文件。当您的程序尝试打开目录进行写入时,它会失败 - 甚至不允许root在目录中写入。 (您可以打开一个目录进行阅读,但实际上无法从中读取;这对于各种*at()函数(例如openat())非常有用,但不是。{/ p>

如果您确实需要文件名中的>,请将整个名称括在引号中:

#。/ tarea1“/ home / pablo /&gt; hello”

但是,您真的不希望文件名中包含>;它只会让生活变得困难(不像文件名中的换行符那么糟糕,但是很接近)。

答案 1 :(得分:0)

你还没有说过你是否使用Linux。但我猜你是。

Linux open有这个非常烦人的功能,由于某种原因,该文件尚不存在,并且您使用的是没有第三个模式参数的open版本,它无法创建该文件。至少那是我发现的。但是,如果文件确实存在且具有适当的权限,则2参数打开调用应该成功。

修复方法是将公开呼叫更改为:

fd=open(argv[1],O_CREAT|O_TRUNC|O_WRONLY,S_IRUSR|S_IWUSR, S_IRWXU)

顺便说一句,我希望你知道如果没有参数,程序会将null传递给open调用。