简体   繁体   中英

how to use-output of callback function on another system command in C

I want to use output of a callback function on another system command. but not working on it, can anybody help?----

#include <stdio.h>
#include <stdlib.h> 
    
int fastLine(const char *filename);

int main() {
    char* ip_file = "f1";  
    fastLine(ip_file); // to print callback   
 
    // want to use it on system command,, but not working
    system("ping fastLine(ip_file)");
        
    return 0;
}

////// 1st line of file callback function ////////
int fastLine(const char *filename) {
    char line[1000];
    FILE *fptr;
    if ((fptr = fopen(filename, "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }
    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", line);
    printf("%s\n", line);   
    fclose(fptr);
    return 0;
}

You need to merge the line read from the file with the ping command using string functions. I've used sprintf() below.

Instead of using a local line variable in fastLine() , you can make this a parameter so that the caller can provide the string to fill in, and then use that as the result.

#include <stdio.h>
#include <stdlib.h> 
    
int fastLine(const char *filename, char *line);

int main() {
    char* ip_file = "f1";  
    char hostname[64];
    fastLine(ip_file, hostname); // to print callback   
    char command[100];
    sprintf(command, "ping %s", hostname);
    system(command);
        
    return 0;
}

////// 1st line of file callback function ////////
int fastLine(const char *filename, char *line) {
    FILE *fptr;
    if ((fptr = fopen(filename, "r")) == NULL) {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }
    // reads text until newline is encountered
    fscanf(fptr, "%[^\n]", line);
    printf("%s\n", line);   
    fclose(fptr);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM