Shepard
Shepard

Reputation: 1111

Space delimited file into structure array C

I would like to store information from file in structure. My file consists of rows (each row has to be different structure) and columns, each column is different data. File looks like this:

1 AB
2 CD
3 CD
4 AB

My structure is this (where node number is first integer and node type is two letter):

struct nodes{
int nodeNumber;
char nodeType[2];
};

My code so far is this:

lines = lineCount(nodes); //calculates how many lines file has
struct nodes node[lines]; //creates structure array
no = fopen(nodes, mode);
if(no == NULL){
    printf("Can't find the files.");
    exit(1);
}else{
    for(i = 0; i < lines; i++){
        fscanf(no, "%d %2c \n", &id, current);
        node[i].nodeNumber = id;
        strcpy(node[i].nodeType, current);
    }
}

when i debug current value is this: current = \"AB\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\" rather than just AB

any ideas?

Upvotes: 1

Views: 272

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409356

The problem is your use of strcpy. It copies string, i.e. character arrays with a terminator. This means that strcpy will copy until it sees the string terminator character '\0' and put that at the end of the array, which means you will overwrite one byte outside of the array.

Either use manual copying character by character, a function such as memcpy, or increase the size of the array to three so it can fit the terminating character (which means you have to make sure the definition of current is also of size three, with a string terminator).

Upvotes: 1

rici
rici

Reputation: 241861

scanf does not nul-terminate characters read with the %c format code. (Although apparently current has lots of NULs, I don't know if you can count on that.

You should declare current as char[2], and use memcpy with a length of 2 instead of strcpy.

Upvotes: 0

Related Questions