我在学校做的实验室有点问题。
它应该做的是检查文件是否存在。当我尝试检查文件是否存在时,除了一行,我的代码工作正常。即使文件存在,它也会返回,好像它总是不存在一样。但是,如果我硬编码到程序中的文件名,它工作正常我只是想弄清楚当我将文件名传递到accept(或者fopen,我已经尝试了这两种方法)时,是什么导致了文件名被错误地解释。
#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);
}
最佳答案
好的,当这样的I/O操作失败时,以及-1,您将得到一个全局int errno;
把你的指纹换成
perror(argv[0]); /* or something else useful. See below */
并添加声明
int errno;
在
#include
和int main
之间,您将收到一条有用的错误消息。(注意:有两件事要检查:确保文件在预期的位置,并使用
ls -l
确保文件可读。)更新
该死的,这就是我没有检查手册的原因
perror
的参数实际上是一个字符串,用于作为错误消息的开头。关于c - 访问总是返回-1,即使文件存在,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6194825/