简体   繁体   中英

Error in printing output when using fscanf in C

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.

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 = %255s Database = %255s Username = %255s 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.

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