Search code examples
cstringfopenfgets

How to remove newline from between strings read from another text file


char IP[32] = "";
char PORT[4] = "0000";

int read_conf()
{
    int i;
    char line[25] = "";
    FILE *fp;
    char *str_ptr;

    fp = fopen("client.conf","r");
    for(i=1;(fgets(line,sizeof(line),fp));i++)
        {
        if(1==i)
            {
            str_ptr = strstr(line,"IP:");
            if(str_ptr)
                {
                strcpy(IP,(str_ptr+3));
                }
            else
                {
                printf("Error in fetching IP \n");
                exit(0);
                }
            }
        else if(2==i)
            {
            str_ptr = strstr(line,"Port:");
            if(str_ptr)
                {
                strcpy(PORT,(str_ptr+5));
                }
            else
                {
                printf("Error in fetching PORT \n");
                exit(0);
                }
            }
        }
    return 1;
}

char *construct_url(int n,char * const argv[])
{
    char * final_url;
    int i,k=2;
    int j = 0;
    final_url = malloc(sizeof(char *)*300);
    strcpy(final_url,"http://");

    strcat(final_url,IP);
    strcat(final_url,":");
    strcat(final_url,PORT);
    strcat(final_url,"/");

    //printf("%s",final_url);
    for(i=1;i<n,k>0;i++,k--)
        {
            strcat(final_url,argv[i]);
            if(i==1)
                {
                strcat(final_url,"/");
                }
            else 
                {
                strcat(final_url,"?");
                }
        }

return final_url; 

}

In my above code it is adding a newline after IP and PORT value which is not correct URL construction. how do I avoid new line before concatenation.
client.conf consist

IP:10.12.130.216
Port:5200

Expected Result:

http://10.12.130.216:5200/

Getting Result:

http://10.12.130.216
:5200
/

Solution

  • read_conf can be written in simple as follows using fscanf.

    char PORT[6] = "00000";//0-65535
    
    int read_conf(void){
        FILE *fp = fopen("client.conf","r");
    
        if(1 != fscanf(fp, "IP:%31s\n", IP)){
            printf("Error in fetching IP \n");
            exit(0);
        }
        if(1 != fscanf(fp, "Port:%5s", PORT)){
            printf("Error in fetching PORT \n");
            exit(0);
        }
        fclose(fp);
        return 1;
    }