frp farhan
frp farhan

Reputation: 449

Command Line Argument processing in c

On running the below code, it stucks after displaying the argv[0], argv[1] and argv[2] line. Further flow of code is blocked at this point, can any one help why it is stopping its execution or is it entering into an infinite loop.

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include "p8log.h"
#include <errno.h>
int main(int argc, char* argv[])
{
        char* PORT;
        char* IPADDR;

        printf("Arg Count=%d\n",argc);
        printf("Arguments are=%s,%s,%s\n",argv[0],argv[1],argv[2]);

        printf("HELLO");

        PORT=argv[1],
        printf("WORLD");
        IPADDR=argv[2];

        printf("START");
        printf("port num=%s",PORT);
        printf("IP ADDR=%s",IPADDR);
        printf("END");

        /* some algorithm of calculation */

        return 0;
}

Execution

./file-exe 11111 127.0.0.1

Output

Arg Count=3

Arguments are=./file-exe,11111,127.0.0.1

Upvotes: 1

Views: 227

Answers (1)

Preston Garrison
Preston Garrison

Reputation: 103

fflush(NULL); is good to do after any output, if you want to make sure it prints to screen. printf is buffered, so it can get lost.

./a.out 11111 127.0.0.1
Arg Count=3
Arguments are=./a.out,11111,127.0.0.1
HELLO
WORLD
START
port num=11111
IP ADDR=127.0.0.1
END

works fine, you needed some \n to break up lines, like so..

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
        char* PORT;
        char* IPADDR;

        printf("Arg Count=%d\n",argc);
        printf("Arguments are=%s,%s,%s\n",argv[0],argv[1],argv[2]);

        printf("HELLO\n");

        PORT=argv[1],
        printf("WORLD\n");
        IPADDR=argv[2];

        printf("START\n");
        printf("port num=%s\n",PORT);
        printf("IP ADDR=%s\n",IPADDR);
        printf("END\n");
        fflush(NULL);
        /* some algorithm of calculation */

        return 0;
}

Upvotes: 1

Related Questions