我將用標準作為開頭:我對 C 編程非常陌生,所以請保持溫和。
我正在撰寫一個 C 程式,它應該能夠將檔案路徑/檔案名作為命令列引數,如果失敗,它應該接受用戶輸入。我的 argv[1] 檔案名正常作業,但如果用戶沒有將檔案名添加為 arg,我不知道如何讓它切換到標準輸入。輸入應該是原始資料,而不是檔案名。這是我的(非常新手)代碼。作為一個新程式員,我可能需要一些解釋的推斷,我為此提前道歉。
int main(int argc, char* argv[]) {
#ifndef NDEBUG
printf("DBG: argc = %d\n", argc);
for (int i = 1; i < argc; i)
printf("DBG: argv[%d] = \"%s\"\n", i, argv[i]);
#endif
FILE* stream = fopen(argv[1], "r");
char ch = 0;
size_t cline = 0;
char filename[MAX_FILE_NAME];
filename[MAX_FILE_NAME - 1] = 0;
if (argc == 2) {
stream = fopen(argv[1], "r");
if (stream == NULL) {
printf("error, <%s> ", argv[1]);
perror(" ");
return EXIT_FAILURE;
}
}
else if (argc ==1)
printf("Enter a list of whitespace-separated real numbers terminated by EOF or \'end\'\n");
//continue with program using user-input numbers
uj5u.com熱心網友回復:
您的代碼過于復雜和錯誤。你做事的順序不對。您首先需要檢查是否存在引數,并僅在這種情況下嘗試打開檔案。
你想要這樣的東西:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
FILE* input = stdin; // stdin is standard input
// so if no arguments are given we simply read
// from standard input (which is normally your keyboard)
if (argc == 2) {
input = fopen(argv[1], "r");
if (input == NULL) {
fprintf(stderr, "error, <%s> ", argv[1]);
perror(" ");
return EXIT_FAILURE;
}
}
else
printf("Enter a list of whitespace-separated real numbers terminated by EOF or \'end\'\n");
double number;
while (fscanf(input, "%lf", &number) == 1)
{
// do whatever needs to be done with number
printf("number = %f\n", number);
}
fclose(input);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431176.html
標籤:C
