對於此程序,我應該將自己的名稱寫入終端或由用戶給出的輸出文件(case 'f'
)。程序未使用命令行上指定的名稱創建文件
#include <stdio.h>
int main(int argc, char **argv)
{
// no output file print to screen, print name to terminal
if (argc < 2)
{
fprintf(stdout, "name\n");
}
//print name to output file given by user
else
{
int option;
int fFlag = 0;
while ((option = getopt(argc, argv, "f:")) != -1)
{
//if case 'f' print to output file
switch (option)
{
case 'f':
fFlag = 1; // flag indicates writing name to file
break;
//case f or error
case '?':
printf("error");
break;
}
}
//write to name to output file
if (fFlag)
{
FILE *file = fopen(argv[1], "w");
fprintf(file, "name");
}
}
return 0;
}
我的代碼工作時,我想我的名字寫入到終端,但是當我想要我的名字寫入到用戶指定的文件不起作用。代碼編譯並運行,但文件不存在。
命令行中的文件可能不存在。我應該在程序中創建文件嗎?
我明白我做錯了什麼。謝謝大家!
您是否(a)檢查到'argv [1]'包含您嘗試打開的寫入訪問的文件名,(b)在嘗試寫入文件之前檢查'file'是否爲非NULL,和(c)假設這兩個平移,確保你的程序正在執行的*當前工作目錄*建立你試圖創建的文件?現在,(a)和(b)似乎是潛在的候選人,後者是違反[Spencer's Sixth Commandment](http://www.seebs.net/c/10com.html) – WhozCraig
的最好例子。通過重新格式化的代碼,它出現'fprintf(file,「name」);'只在'argc <2'的情況下 – chux
除了以前的評論,我認爲你也忘了在寫完fclose(file)之後。 –