What I’m trying to do is to write a function that creates a file, fills it with data and returns the file to main(). The question is – what is the right way to “return file”. Should I pass pointer / file descriptor or just disregard all this and use filename?
EDIT: doing the right way (I hope):
int mkrandfile(const char *name, int range, int qnt)
{
FILE *afile;
int i = 0;
if (afile = fopen(name, "w+"))
{
while((i <= qnt) && fprintf(afile, "%d ", rand() % range - range/2))
i++;
fclose(afile);
if (i != qnt + 1)
return -2;
}
else
return -1;
}
You are correct that returning
afilefrom that function is wrong. Once the file is closed, that file handle is no longer valid. Use of it by the caller would result in undefined behavior.While it is probably not the best idea from a modularity standpoint, you could leave the file open and then return the handle. But I think one of the following might be better:
The first option may be more efficient when file caching by the OS (if applicable here) is considered.