简体   繁体   中英

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:

#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'. as below:

redirect> programname.txt

Now this IS generating a file 'programname.txt' on the desktop, but it is empty. 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. 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. 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.

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.

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. 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 ). In that case, you can redirect its output by saying:

./foo > filename.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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