问题描述
|
我正在为学校工作的实验室出现问题。
它应该做的是检查文件是否存在。当我尝试检查文件是否存在时,我的代码可以正常工作,只有一行。即使文件存在,它也会返回,好像并不总是存在。但是,如果我将文件名硬编码到程序中,则可以正常工作。我只是想弄清楚是什么原因导致将文件名传递给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失败时,结果为全局global1ѭ
如果您有打印文件,请替换为
perror(argv[0]); /* or something else useful. See below */
并添加声明
int errno;
在ѭ4和ѭ5之间,您会收到一条有用的错误消息。
(PS:需要检查两件事:确保文件位于您期望的位置,并使用ѭ6键确保文件可读。)
更新资料
该死,这就是我不检查手册页而得到的。 perror
的参数确实是一个字符串,用于在错误消息前添加前缀。
, 在此语句中:
fgets(filetocheck,120,file);
您可能会在文件检查缓冲区中收到不必要的回车符。