简体   繁体   English

为什么该程序不能与C中的OS重定向命令一起使用?

[英]Why won't this program work with the OS redirection command in C?

I am working with command prompt features with a simple program to generate a text file in C. Here is the program: 我正在使用一个简单的程序来使用命令提示符功能,以在C中生成文本文件。这是该程序:

#include <stdio.h>

int main(void)
{
    char buf[80];

    fgets(buf, 30, stdin);
    printf("the input was %s\n", buf);
    return 0;
}

My programming book is wanting to show how to play with the command prompt to make text files from programs, and instructs typing the word 'redirect' followed by '>' then the name of the program name with '.txt'. 我的编程书想展示如何在命令提示符下播放程序中的文本文件,并指示键入单词“ redirect”,后跟“>”,然后键入程序名称,并带有“ .txt”。 as below: 如下:

redirect> programname.txt

Now this IS generating a file 'programname.txt' on the desktop, but it is empty. 现在,这正在桌面上生成文件“ programname.txt”,但它为空。 The book purports that recipe should allow me to enter a string (as the program is DESIGNED to do) and that this string will be inside a generated programname.txt file. 这本书声称配方应该允许我输入一个字符串(因为该程序是设计来执行的),并且该字符串将位于生成的programname.txt文件中。 Also, there is a warning in the command line: "not recognized as an internal or external command". 此外,命令行中还会显示一条警告:“未识别为内部或外部命令”。 I've had this schpill before, but the text file generation did WORK, in that it did generate the .txt file. 我以前有过这个schpill,但是文本文件的生成确实起作用,因为它确实生成了.txt文件。 What am I missing here, for this program to work as intended? 为了使该程序按预期工作,我在这里缺少什么?

You seem to be confused by the fact that it is not your program, but the shell which creates the file programname.txt , before it even tries to run your program. 您似乎对这个事实感到困惑,因为它不是您的程序,而是在甚至试图运行程序之前创建文件programname.txt的外壳。

And after the first succeeded and created an empty file, the latter probably fails because there is no command redirect in your PATH or such a thing exists as a builtin in your shell, as has already been suggested. 在第一个成功并创建了一个空文件之后,后者可能会失败,因为您的PATH中没有命令redirect ,或者如您所建议的那样,shell中存在内置的东西。

The usual way to perform output redirection in a shell is to use the > filename , but not with redirect before it contrary to what you say. 在shell中执行输出重定向的通常方法是使用> filename ,但与您所说的相反,不能在redirect之前使用redirect The thing that comes before the > is the command to be redirected. >之前的是要重定向的命令。

So, let's say you compile your program and save it as foo in the current directory (eg cc -o foo myprogram.c ). 因此,假设您编译了程序并将其另存为foo在当前目录中(例如cc -o foo myprogram.c )。 In that case, you can redirect its output by saying: 在这种情况下,您可以通过以下方式重定向其输出:

./foo > filename.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM