Reputation: 19
I am trying to write a program that reads data from a file and puts it into a struct array. I have succeeded in putting it into the array but I then get a segmentation fault. I believe I have to use malloc to initialize the struct array but I am new to programming and don't really understand how to do this. Thanks for your help! I have copied pieces of my code so you can see what I've done. I have not included my functions in this code.
struct Weather
{
char location;
int daynum;
double temp;
double precip;
};
int main (void)
{
FILE*openFile;
char buffer[COLS][ROWS];
int i = 0;
struct Weather loc1; //initialize here?
for (i = 0; i <200; i++)
{
fgets (buffer[i], ROWS, openFile);
parseLine(buffer[i], &loc1);
printf ("%d %c %d %.2lf %.2lf\n",i, loc1.location, loc1.daynum, loc1.temp, loc1.precip);
}
}
Upvotes: 1
Views: 306
Reputation: 144951
Multiple problems in your code:
The stream pointer openFile
is uninitialized, calling fgets()
for it invokes undefined behavior. You want to open a file for fopen()
or set the value of openFile
to the standard input stream stdin
.
The 2D char
array should be defined in the other order:
char buffer[ROWS][COLS];
you should use the same constant for the loop counter and the 2D array definition: ROWS
might be defined to something less than 200
.
the size of the line buffer is COLS
, pass that to fgets()
.
you should test the return value of fgets()
: it returns NULL
at end of file and the contents of the destination array is indeterminate in this case.
whether or not to initialize loc1
depends on what the parseLine()
function does. It would make sense that parseLine()
make no assumptions about the contents of the destination structure, but the source has not been posted, so we cannot know for sure.
the printf
format specifier for type double
is %f
, the extra l
is simply ignored.
Upvotes: 0
Reputation: 388
You must initialize the file stream with fopen()
before any I/O operations!
int main()
{
char filename[64];
FILE *fp;
snprintf(filename, sizeof(filename), "hello1234.txt");
if(NULL == (fp = fopen(filename, "r")))
{
printf("err, failed when fopen(), %s %s[%d].\n", __FILE__, __FUNCTION__, __LINE__);
return -1;
}
//your code here
return 0;
}
Initialize the struct
Note that malloc()
cannot initialize the struct.
two methods:
M0:
struct Weather loc1; memset(&loc1, 0, sizeof(struct Weather));
M1:
struct Weather loc1 = {0};
man malloc
or click the link for a malloc manual.
Upvotes: 1