Home > Software design >  Error in printing output when using fscanf in C
Error in printing output when using fscanf in C

Time:11-12

Here's a code I have been working on C.

char Host_ip[256];
char *Database_name;
char *Username;
int listen_port;

FILE *myfile = fopen("Coin_Converter.config", "r");
fscanf(myfile, "Host=%s Database=%s Username=%s listenport=%d", Host_ip, Database_name,
                                                Username, &listen_port);
fclose(myfile);

printf("Host = %s", Host_ip);
printf("Username= %s", Username);
printf("Database= %s", Database_name);
printf("listenport = %d", listen_port);

My config file looks like this:

Host = 127.0.0.1
Database = base20
Username = John
listenport = 8080

I don't have any issue with compiling the code but I am not able to print anything. Infact, when I only print Host_ip it's working but otherwise I am not getting anything. I tried few things but I can't figure out what I am doing wrong.

CodePudding user response:

Two main mistakes in your code are

  • Using unallocated pointers instead of buffers

  • Not filtering whitespace from the input stream.

With some changes (commented) the code becomes

#include <stdio.h>

int main()
{
    char Host_ip[256];
    char Database_name[256];        // array instead of pointer
    char Username[256];             // array instead of pointer
    int listen_port;

    FILE *myfile = fopen("Coin_Converter.txt", "r");
    if(myfile == NULL)
        return 1;
    fscanf(myfile, "Host = %5s Database = %5s Username = %5s listenport = %d",
                Host_ip, Database_name, Username, &listen_port);    // added spaces
    fclose(myfile);

    printf("Host = %s\n", Host_ip);             // added newlines
    printf("Username= %s\n", Username);
    printf("Database= %s\n", Database_name);
    printf("listenport = %d\n", listen_port);
}

and outputs

Host = 127.0.0.1
Username= John
Database= base20
listenport = 8080

The added spaces in the fscanf format string are to remove any whitespace (or none) from the input stream.

  • Related