這裏有很多錯誤。
致電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