我的程序读取标准输入并将其存储到char数组cmd中,然后调用system(cmd)。我把它打印出来,它的内容正是我所期望的。但是cmd不会保存system(cmd)中的内容。我尝试使用存储在report.log中的文本字符串,这次成功了。那么cmd2有什么问题?
我用的是Windows 8。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <stdarg.h>
#include <time.h>

#define MAXLEN 100


char *now(){
    time_t t;
    time(&t);
    return asctime(localtime(&t));
}

int main(int argc, char *argv[])
{
    char comment[80];
    char cmd[120];

    fgets(comment, 80, stdin);
    sprintf(cmd, "echo '%s %s' >> report.log", comment, now());

    printf("%s", cmd); // content of cmd is what I expect

    system(cmd); // does not work, why?

    char cmd2 = "echo 'Hello world' >> report.log";
    system(cmd2); // work


    return 0;
}

最佳答案

您的问题可能是\n的输入中存在多余的sprintf()s。
fgets()扫描并存储\n中的stdin。你需要去掉这个\n并用空值替换它。
asctime()返回一个ctime()返回样式字符串,再次以换行符结束。你也需要把它移走(换掉)。
您可以检查以下代码以供参考。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>

#define MAXLEN 100


char *now(){
    time_t t;
    time(&t);
    return asctime(localtime(&t));
}

int main(int argc, char *argv[])
{
    char comment[80] = {0};
    char cmd[120] = {0};
    char * timestring = NULL;   //initialize local variables, good practice

    fgets(comment, 80, stdin);
    comment[ strlen(comment) -1] = 0;       //reomve the trailing \n taken by fgtes(), replace by null

    timestring = now();
    timestring[strlen(timestring)-1] = 0;   //remove the \n from ctime() return style string, replace b null

    sprintf(cmd, "echo '%s %s' >> report.log", comment, timestring);

    printf(">> The string is : %s\n", cmd);

    system(cmd); // should work now.. :-)

    return 0;
}

关于c - system()不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29204591/

10-11 20:14
查看更多