简体   繁体   English

无法打开文件C.

[英]Unable to open file C

For the following snippet of code, I get an error: 对于以下代码片段,我收到一个错误:

Unable to open file: No such file or directory

redirect_ptr is char** And I have tried printing redirect_ptr[0], it prints it correctly. redirect_ptr是char **我尝试打印redirect_ptr [0],它正确打印。 Any idea where the problem might lie? 知道问题可能在哪里吗?

if ((in_fd = open(redirect_ptr[0], O_RDWR | O_CREAT)) == -1) {
   perror("Unable to open file");
   return -1;
}

When you create a file, open() needs an additional argument, the permission bits on the file to create. 创建文件时,open()需要一个额外的参数,即要创建的文件的权限位。 You need to do eg 你需要做例如

if ((in_fd = open(redirect_ptr[0], O_RDWR | O_CREAT, 0644) == -1) 

That might not be the cause of the error you get, however if the error is "No such file or directory", then that's precisely what is wrong, you program cannot find the file. 这可能不是你得到的错误的原因,但是如果错误是“没有这样的文件或目录”,那么这正是错误的,你的程序找不到该文件。

Perhaps you have some non-printable characters in the file name, or the name ends with a space or newline or similar, or you spelled the name wrong, or have the wrong case, or the path is a relative path that doesn't match the file based on the current working directory of your process. 也许您在文件名中有一些不可打印的字符,或者名称以空格或换行符或类似名称结尾,或者您拼写错误的名称,或者包含错误的大小写,或者路径是不匹配的相对路径该文件基于进程的当前工作目录。

It's often helpful to print the filename inside a pair of '' , so you can see if there's some whitespace that should not be there. 在一对''中打印文件名通常很有帮助,所以你可以看到是否有一些不应该存在的空白。 add a 添加一个

 printf("Filename: '%s'\n",redirect_ptr[0]);

to your code. 你的代码。 And if it looks good, do a ls -l on the filename it prints out, standing in the working directory of the process. 如果看起来不错,请在打印出来的文件名上执行ls -l,站在进程的工作目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM