My assignment right now is actually in a computer graphics class, but I can't even get to that before I ran into several problems. Firstly, the program needs to parse an input file to get data about some output file name, some resolution numbers in floats and some in ints. There can also be blank lines and comments which are started by a "#". There are seemingly so many places I'm doing things wrong so I figured I'd try to get some help from programmers before I embarrass myself turning this in (even if it works) using really messy syntax and deprecated functions, etc.
Firstly I'm not sure what is considered the "best" way to reading file input. Right now I'm using a function that I wrote just to try to parse a valid piece of data, and I'm not even sure if what I'm using is correct in that:
char * getLine(FILE * fp )
{
char line [80];
while(fgets(line,80,fp) != NULL)
{
//Look for non-empty line
if(line[0] != "\n" && line[0] != "#")
{
return line;
}
sscanf(line, "%s#", line);
}
//If at EOF, return null
return NULL;
}
Here I'm using fgets, and not even sure if I'm using it correctly. :(
Next issue I'm having is that when I am having an int or float taken from my program, I'm trying to figure out the best way to parse that. I'm currently using atof or atoi, such as in this example:
shapes[i].r = atof(getLine(fp));
I've heard that using these are bad, though I've also found a lot of people suggesting using them while I was googling around. Which is it? And what exactly is the "correct" way to do this?
Also, for this I need to error check every line of input I get from the file to ensure it's valid. After each call to getLine, I put in an if statement to check for bad data, such as this:
if(shapes[i].r > 1.0 || shapes[i].r < 0.0)
{
printf("Invalid red value in shape #%d\n", i);
fclose(fp);
freeData(shapes, nshapes);
return 1;
}
But I'm wondering if there is an easier way to do this in C multiple times, rather than having to write one of these error check if statements for every line of input. I could check the bounds individually and write print statements, but it seems unnecessary to have to write out calls to fclose and return in every one. (And I shudder to think of the idea of a go to statement)And for my final question, I seem to fail to remember how dynamic memory allocation and freeing works. If I have a struct which contains a pointer to a struct, both of which are dynamically allocated, do I have to go through an array of that first struct and free each sub-struct and then free the main struct array, or does freeing the array/array pointer also free things inside of the structs?
God I feel like such a noob. >_<


Sign In
Create Account

Back to top









