如何编辑使用系统命令创建的C中的文本文件?

时间:2017-06-11 17:31:58

标签: c file-handling

我写了一个程序来打印" Traceroute"的输出。在linux终端上运行的命令。代码如下:

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

#include "SourceIP.c"
#include "RandomTraceroute.c"
#include "Time.c"

int main()
{
    unsigned char sourceIP[15];
    source(sourceIP);   
    printf("%s\n",sourceIP);

    unsigned char destIP[15];
    randIP(destIP); 
    printf("%s\n",destIP);

    char buff[100];
    timestamp(buff);
    printf ("%s\n", buff);

    char buf[BUFSIZ];
    snprintf(buf, sizeof(buf),"traceroute -q 1 %s >output.txt",destIP);
    system(buf);

    return 0;
}

任务是通过删除文本文件的现有第一行,将前三个printf行打印为output.txt文件的前三行。任何人都可以为此提出答案。 (请考虑代码的时间复杂度)

1 个答案:

答案 0 :(得分:0)

您如何看待以下代码:

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

#include "SourceIP.c"
#include "RandomTraceroute.c"
#include "Time.c"

int main()
{
    FILE *f = fopen("output.txt", "w");

    unsigned char sourceIP[15];
    source(sourceIP);   
    fprintf(f, "%s\n", sourceIP);

    unsigned char destIP[15];
    randIP(destIP); 
    fprintf(f, "%s\n", destIP);

    char buff[100];
    timestamp(buff);
    fprintf(f, "%s\n", buff);

    fclose(f);

    char buf[BUFSIZ];
    snprintf(buf, sizeof(buf),"traceroute -q 1 %s 2> /dev/null >> output.txt", destIP);
    system(buf);

    return 0;
}