[英]How to redirect stdout and stdin in a given file using argv in C
[英]Using stdin and stdout if no file is given in C
我有一个将源文件复制到目标文件的程序。
如果用户只提供 1 个文件或这些文件都不提供,我想使用 stdin 或 stdout。
例如:命令行参数中没有提供源文件名,但目标文件提供了。 程序应该从标准输入读取输入并写入给定的目标文件。
我知道freopen()
但我不知道在这种情况下我应该如何使用它。
下面是我认为逻辑完成方式的样板代码,但我找不到任何有助于我学习的示例。 任何见解都值得赞赏。
char *src = NULL; (unless user provides in preceding code not shown)
char *dest = NULL; (^^)
// open files based on availability
// src and dest not provided, read from stdin and write to stdout
if (src == NULL && dest == NULL) {
FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
// TODO
fclose(in);
fclose(out);
// src not provided, read from stdin
} else if (src == NULL) {
FILE *in = freopen(src, "r", stdin);
// TODO
fclose(in);
// dest not provided, write result to stdout
} else {
FILE *out = freopen(dest, "w", stdout);
// TODO
fclose(out);
}
我倾向于避免使用
freopen<\/code>并使用不同的方法。
我定义了 2 个
FILE *<\/code>变量,如果提供了文件名,则使用
fopen()<\/code>如果没有,则将它们设置为适当的
stdin<\/code>或
stdout<\/code> :
#include <stdio.h>
/* copying files: 0, 1 or 2 arguments */
int main(int argc, char *argv[]) {
FILE *in = stdin;
FILE *out = stdout;
char *srcfile = NULL;
char *destfile = NULL;
int c;
if (argc > 1) {
srcfile = argv[1];
if (argc > 2)
destfile = argv[2];
}
if (srcfile && strcmp(srcfile, "-")) {
if ((in = fopen(srcfile, "r")) == NULL) {
perror(srcfile);
return 1;
}
}
if (destfile && strcmp(destfile, "-")) {
if ((out = fopen(destfile, "w")) == NULL) {
perror(destfile);
return 1;
}
}
while ((c = getc(in)) != EOF) {
putc(c, out);
}
if (in != stdin)
fclose(in);
if (out != stdout)
fclose(out);
return 0;
}
只是 if 语句就是这样。 验证 src 是否为 NULL,如果是
fopen(src, "r", stdin)<\/code>但不要在之后关闭它,否则会导致未定义的行为(我说的是
stdin<\/code> )。
对于
stdout<\/code> ,您甚至不必打开它,因此您可以像那样在其中写入。
例子:
int is_in = src == NULL;
FILE *in = fopen(src, "r", is_in ? stdin : src)
if (!is_in)
fclose(in);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.