From file to structure in C

2019-06-08 10:24发布

问题:

I am trying to write from file to structure in C. Whenever I try to assign value in structure it gives me error: incompatible types in assignment.

My structure looks like this:

struct competition{
char eventTitle[79];
char date[79];
char time[79];
};

Basically I want to open the file and assign individual line to different value in structure. ie. first line in file -> eventTitle, second line -> date, third line -> time.

Here is how I try to assign it:

FILE *naDaSt;
char *mode = "r";
int lines = 0;
char line[79], current[79];


naDaSt = fopen(nameDateStart, mode);
if(naDaSt == NULL){
    printf("Can't find the files.");
    exit(1);
}else{
    struct competition comp, *p;
    p = ∁
    while(fgets(line, 79, naDaSt)){
        lines++;
        if(lines == 1){
            p->eventTitle= line;
        }
        if(lines == 2){
            p->date = line;
        }
        if(lines == 3){
            p->time = line;
        }
    }
}    

}

Could anyone help me?

回答1:

Root Cause:

You cannot do this:

        p->eventTitle = line;
        p->date = line;
        p->time = line;

You are trying to assign arrays using assignment which cannot be done, arrays need to be copied. The compiler rightly reports the error:

error: incompatible types in assignment

because indeed the type you are trying to assign are incompatible.

Solution:

Instead, You need to use strcpy and copy the character arrays and not assign them.



回答2:

You can't assign to an array like that in C:, you need to copy the values into the array using one of the copy functions:

strcpy()
strncpy()  // This one is better to use

http://linux.die.net/man/3/strcpy

Another thing to consider, you have the literal number 79 in your code more than a few times and it appears to denote the size of all of your arrays. It would be simpler to define an array length that can be used for all of them:

#define LENGTH 79

struct competition
{
  char eventTitle[LENGTH];
  char date[LENGTH];
  char time[LENGTH];
};

You can even use this constant when reading in your fgets and eventual strncpy() calls:

while(fgets(line, LENGTH, naDaSt))
strncpy( ..., ..., LENGTH);


回答3:

This question has basically been answered on a similar posting. See link.

Reading File and Populating Struct



回答4:

I would not recommend using strncpy() function. It has its quirks, does not append the trailing \0. You must copy character arrays(strings) from one location to another using strcpy().