Slim Hmidi Slim Hmidi - 1 year ago 63
C Question

Empty file when using sprintf and system function on C

I want to save some information in a file text, I wrote this program:

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

int main(int argc,char *argv[])
FILE *fichier;
char buffer[20];
char command[200];
char command1[100];

system(" cat /etc/resolv.conf | grep nameserver | awk -F' ' '{print $2}' | cut -d'.' -f1-3 | awk '{print $1\".1\"}' > ethernet_dns.txt");

printf("buffer is: %s",buffer);

snprintf(command,sizeof(command),"ping -c 1 -W 1 %s > /tmp/ping_result",buffer);
printf("command is: %s",command);


return 0;


buffer is:
command is : ping -c 1 -W 1

the system command returns this:

PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=0.115 ms

--- ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.115/0.115/0.115/0.000 ms

But when I run : cat /tmp/ping_result.I got an empty file

Answer Source

Problem: Code is reading '\n' into buffer[] yet trying to that as part of the command. Need to trim the buffer. *** below

 // Insure file is open

 // Use fgets
 if (fgets(buffer, sizeof buffer, fichier)) {

   // lop off potential \n
   buffer[strcspn(buffer, "\n")] = '\0';  // ***

   printf("buffer is: <%s>\n",buffer);

   int n = snprintf(command, sizeof(command), "ping -c 1 -W 1  %s > /tmp/ping_result", 
   printf("command is: <%s>\n",command);

   // Only issue command if no problems occurred in snprintf()
   if (n > 0 && n < sizeof(command)) system(command);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download