J. Homer
J. Homer

Reputation: 147

Reading random input from file

I have a file and I want to read some random input from file, I don't want to use getline or some things like that, the scanning works but it reads some random stuff, like null or different characters. I think the problem could be when i am reading a single character and that might destroy all this.

Here is some code to see what I did:

#include <stdio.h>
#include <stdlib.h>

typedef struct queries
{
    char type;
    int node;
    char *addr;
} Queries;

int main()
{
    int i;
    FILE *f;

    f = fopen("queries.in", "r");

    if (!f)
    {
        fprintf(stderr, "File queries.in was not opened correctly.\n");
        exit(1);
    }

    int n_queries;

    fscanf(f, "%d\n", &n_queries);

    Queries *q = (Queries*)malloc(n_queries*sizeof(struct queries));

    for (i = 0; i < n_queries; ++i)
    {
        fscanf(f, "%c ", &q[i].type);
        if(q[i].type == 'q')  fscanf(f, "%d %s\n", &q[i].node, q[i].addr);
        else fscanf(f, "%d\n", &q[i].node);
    }

    for (i = 0; i < n_queries; ++i)
    {
        printf("%d %c ", i, q[i].type);
        if(q[i].type == 'q') printf("%d %s\n", q[i].node, q[i].addr);
        else printf("%d\n", q[i].node);
    }

    fclose(f);
}

And here is the input:

8
q 0 addr2
q 0 addr1
q 0 addr1
q 1 addr4
q 1 addr1
q 1 addr2
f 4
q 1 addr4

Well expected output:

8
q 0 addr2
q 0 addr1
q 0 addr1
q 1 addr4
q 1 addr1
q 1 addr2
f 4
q 1 addr4

Actual output:

0 q 0 (null)
1 a 0
2 d 0
3 d 0
4 r 2
5 q 0 (null)
6 a 0
7 d 0

I have no idea what's going on

Upvotes: 0

Views: 49

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

When you fscanf into q[i].addr, there has not yet any memory been allocated to q[i].addr. Now anything can happen because the string is placed in memory that is not yours.

You should also check the return value of fscanf to be suer the data was properly read.

Upvotes: 1

Related Questions