Piyumi Guruge Piyumi Guruge -4 years ago 43
C Question

How to edit a text file in C created with a system command?

I have written a program to print the output of the "Traceroute" command that run on the linux terminal. Here the code:

#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;
}


The task is to print this first three printf lines as the first three lines of the output.txt file by removing the existing first line of the text file. Can anyone suggest an answer for this.
(Please consider about the time complexity of the code also)

Answer Source

What do you think about following code:

#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;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download