对于我正在上学的实验室,我遇到了一些问题.它应该做的是检查文件是否存在.当我尝试检查文件是否存在时,我的代码工作正常,除了一行.即使文件存在,它也会返回,就好像它不存在一样.然而,如果我将文件名硬编码到程序中,它可以正常工作.我只是想弄清楚当我把它传递给accept时导致文件名被解释错误的原因(或者我已经尝试过两次).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
//open lab4.in
FILE *file = fopen("lab4.in", "r");
if (file == 0) {
printf("Unable to open lab4.in for reading");
exit(-1);
}
//get the file name to check
char filetocheck[120], output[12];
fgets(filetocheck, 120, file);
int i;
//open lab4.out for writing
unlink("lab4.out");
FILE *write = fopen("lab4.out", "w");
fgets(output, 12, file);
//check the file is there and write the characters to lab4.out
if (access(filetocheck, F_OK) == -1){
for (i=5; i<10; i++){
fputc(output[i], write);
}
} else {
for (i=0; i<5; i++){
fputc(output[i], write);
}
}
//close the files at the end
fclose(write);
fclose(file);
Run Code Online (Sandbox Code Playgroud)
}
好的,当像这样的I/O操作失败时,以及-1,你会得到一个全局的结果 int errno;
如果你有printf,请用它替换
perror(argv[0]); /* or something else useful. See below */
Run Code Online (Sandbox Code Playgroud)
并添加声明
int errno;
Run Code Online (Sandbox Code Playgroud)
您之间#includeS和int main,你会得到一个有用的错误消息.
(PS:要检查的两件事:确保文件位于您期望的位置,并ls -l确保其可读性.)
更新
该死,这是我没有检查手册页得到的.参数to perror确实是一个字符串,用于序言错误消息.