我将用标准来说明这一点:我对C编程非常陌生,所以请温柔一点。
我正在编写一个C程序,它应该能够将文件路径/文件名作为命令行arg,否则它应该接受用户输入。我的argv1文件名可以工作,但是如果用户没有将文件名作为arg添加,我不知道如何让它切换到stdin。输入应该是原始数据,而不是文件名。这是我的(非常新的)代码。作为一个新的程序员,我可能需要一些外推法的解释,我对此表示歉意。
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 发布于 2022-02-22 16:56:42
您的代码过于复杂和错误。你做的事情顺序不对。首先,您需要检查是否存在参数,并尝试只在这种情况下打开文件。
你想要这样的东西:
#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://stackoverflow.com/questions/71225026
复制相似问题