简体   繁体   English

如何在C中将命令行写入文件

[英]how to write a command line to a file in c

I'm having issues with writing this command line to a file and it's suppose to output to the screen. 我在将此命令行写入文件时遇到问题,并且应该输出到屏幕上。 To me, my code looks like it should work but I'm at a complete loss (this is my first time programming in C) 对我来说,我的代码看起来应该可以工作,但是我完全不知所措(这是我第一次使用C语言编程)

Print one line describing your program 打印一行描述您的程序

Open the first parameter as a file for writing. 打开第一个参数作为要写入的文件。 If no parameter is provided, write to the stdout handle 如果未提供任何参数,则写入标准输出句柄

Using a loop, save the contents of the array of string pointers passed as a parameter to the main function into the file open for writing. 使用循环,将作为参数传递给主函数的字符串指针数组的内容保存到打开的写入文件中。 This is usually the variable named argv. 这通常是名为argv的变量。

int main(int argc, char *argv[])
{
    FILE *fp;
    int i;
    printf("Output supplying 'multiple arguments' to this program");

    fp = fopen(argv[1], "w"); //Write to file
    if(fp==NULL)
    {
           fp = stdout;
    }

    for(i=0;i<argc;i++)
    {
           fprintf(fp, argv[i]);
    }

    printf("The number of arguments printed %d", argc);

    return 0;

Any help provided would be greatly appreciated! 提供的任何帮助将不胜感激!

Don't ever use dynamic format strings in C. This opens you up to an extensive set of bugs, several of them security-sensitive. 永远不要在C中使用动态格式字符串。这会给您带来大量的错误,其中一些对安全性敏感。 Instead, pass a format string that indicates your intent, like so: 而是传递表示您意图的格式字符串,如下所示:

for(i=0;i<argc;i++)
{
       fprintf(fp, "%s\n", argv[i]);
}

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

相关问题 如何用C编写一个简单的命令行工具? - How write a simple command line tool in C? 在C语言中,如何将-o用作命令行参数,以将输出写入另一个文件而不是stdout? - In C, how do I incorporate -o as a command line paramenter, to write output to another file rather than stdout? 如何在命令行上执行ac文件 - How to execute a c file on the command line 如何编写包含在 C 中作为命令行参数给出的换行符的文本? - How to write text containing newline given as command line arguments in C? 如何从命令行编写一个 c 程序,它将 2 个字符串作为 arguments? - How to write a c program that takes 2 strings as arguments from the command line? 如何在* C *中围绕命令行程序编写GUI包装? - How to write a GUI wrapper around a command line program in *C*? 如何在ac文件中写入入口点,以便可以通过命令行和/或WSTP / MathLink / Mathematica访问文件的其他功能? - How do I write the entry point in a c file such that the file's other functions can be accessed via command line and/or WSTP/MathLink/Mathematica? 在C中将空白行写入文件 - Write blank line to file in C linux命令行在ac文件中 - linux command line in a c file 逐行写入文本文件 c - Write into text file line by line c
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM