我创建了一个名为"test“的文件,但我无法使用fopen打开它。这是代码-
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("test.txt","r");
if(fp==NULL)
{
perror("Error: ");
}
fclose(fp);
return 0;
}当我运行上面的代码时,我得到以下输出:
Error: Invalid argument可能的原因是什么?当perror返回“无效参数”错误消息时?
发布于 2014-11-04 20:24:30
看一看man fopen
EINVAL提供给fopen()、fdopen()或freopen()的模式无效。
可能test.txt是不可读的。
发布于 2014-11-04 21:14:18
尝试使用-g进行编译。这让您可以使用gdb一步一步地调试程序;查看如何使用它。可能更好的方法是使用stat(2)。以下代码示例将在文件不存在或不是常规文件时返回错误:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
struct stat s;
int check = stat("test.txt", &s);
if(check != 0){
printf("ERROR: File does not exist!\n");
return -1;
}
return 0;
}Stat存储了大量关于文件的信息(如长度、类型等)在struct stat中,在本例中命名为"s“。它还返回一个整数值,如果文件不存在,则该值为非零值。
https://stackoverflow.com/questions/26735029
复制相似问题