I am trying to read in values from a file and store them in a structure.
The structure contains
char region
char country[100]
int country_code
The instance of this structure is called c[100]
The file i am trying to read in looks like this
Europe
0 France
1 England
2 Germany
There are an unkonwn number of countries, so it has keep reading until EOF.
I have created an array of the structures.
The code i have so far looks like this:
fp= fopen(countries,"r");
while (!feof(fp))
{
fscanf(fp, "%[^\n]", c.region);
while (!feof(fp))
{
fscanf(fp, "%d, %[^\n]", c[i].country_code, c[i].country);
i++;
}
}
I get a segmentation fault. I'm sure its something obvious that开发者_JAVA技巧 ive missed out or done wrong, but im not sure what, and i would be grateful if anyone could help.
fscanf(myfile, "%d, %[^\n]", c[i].country_code, c[i].country);
should be fixed to
fscanf(myfile, "%d, %[^\n]", &(c[i].country_code), c[i].country);
as fscanf needs an address to write data. You do not need to use &
for char array, as it is already a pointer.
Also, in your structure char region;
should be changed to char region[100];
as you have not the one char for the region, but several ones, IOW a string.
myfile = fopen(countries,"r");
Check the return value for errrs
while (!feof(myfile))
{
fscanf(myfile, "%[^\n]", c.region);
You need to pass the address of c.region: &c.region
. However, it's still wrong as you're only allocating one character and fscanf will read characters until a non-match. You should change the declaration of c.region to be a character array c.region[[00]
or something.
Also, c is an array, not a struct, so I don't think this is the code you're actually using. Did you mean c[0].region?
You should also worry about reading more than whatever you have allocated. Read up on fscanf's ways of limiting what it stores in the address passed
Where do you set i to zero?
while (!feof(myfile))
{
fscanf(myfile, "%d, %[^\n]", c[i].country_code, c[i].country);
Again, you need to pass the address of the country_code field &c[i].country_code"
. Note that you do not need to use the & operator on the country field, even though the other answers so far say you do as country is a char array and so c[i].country is the same as &c[i].country
i++;
What happens if there are more lines in the file than allocated entries in the c[i] array?
You need to take the address of the country_code and country fields:
fscanf(myfile, "%d, %[^\n]", &c[i].country_code, &c[i].country);
Otherwize fscanf will intepret those two integer values as pointers, and try storing data into them => segmentation fault.
with struct like
char region[100]
char country[100]
int country_code
it should work eg.
char aregion[100]="", line[100];
...
while( fgets(line,100,myfile) )
{
if( *aregion && 2==sscanf(line,"%d%99[^\n]",&c[i].country_code,c[i].country) )
strcpy(c[i++].region,aregion);
else
if( !strchr(line,' ') )
sscanf(line,"%99[^\n]",aregion);
}
精彩评论