这里有很多错误。
致电fopen()
后,您应该检查pf
是否为NULL
,因为fopen()
可能会失败。
您正在试图打开名称filename+.txt
的文件。你不应该打开名称作为参数提供的文件吗?
另外,main()
的结构应该是int main(int argc, char **argv)
,你不能做任何你想做的事情。
检查argc > 1
,在这种情况下程序是以参数启动的,文件名应该在argv[1]
中提供。
更新的评论:这是你的代码看起来应该像:
int main()
{
char filename[512]; // reserve 512 bytes to receive the file name from input
FILE *pf;
int ii;
int jj;
printf("Enter file name: ");
scanf("%s", filename);
pf = fopen(filename, "r");
if (pf)
{
fscanf(pf,"%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", filename);
}
return 0;
}
你也可以做到这一点,以获得从参数文件名:
int main(int argc, char **argv)
{
FILE *pf;
int ii;
int jj;
if (argc > 1)
{
pf = fopen(argv[1], "r");
if (pf)
{
fscanf(pf, "%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", argv[1]);
}
}
else
{
printf("Insuficient parameters");
}
return 0;
}
甚至,如果你不不想通过文件扩展名:
int main(int argc, char **argv)
{
char *filename;
FILE *pf;
int ii;
int jj;
if (argc > 1)
{
filename = malloc(strlen(argv[1]) + 5); // alloc necessary memory
strcpy(filename, argv[1]);
strcat(filename, ".txt");
pf = fopen(filename, "r");
if (pf)
{
fscanf(pf, "%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", filename);
}
}
else
{
printf("Insuficient parameters");
}
return 0;
}
你已经完全错误的主要方法签名 – rpeshkov
在fopen中,第一个参数应该是文件名,没有“和其他调整你键入。因此,你会期望一个分段错误 – gnometorule
而现在,你的最后一段不介绍你如何使用这个程序:不是,只需键入./readfile如果以该名称(不CMD线PARAM)编译它 – gnometorule