[Question 1]
When I open a file into a function, generally I do something like this:
int read_file (char *filename)
{
FILE *fin;
if ( !(fin = fopen(filename, "r")) )
return 1;
/* ... */
return fclose(fin);
}
int main ()
{
char filename[100];
if ( read_file(filename) )
{
perror(filename);
exit(1);
}
return 0;
}
Generally 0
return value is for errors (right?) then I can change the previous code into:
int read_file (char *filename)
{
FILE *fin;
if ( !(fin = fopen(filename, "r")) )
return 0;
/* ... */
return !fclose(fin);
}
int main ()
{
char filename[100];
if ( !read_file(filename) )
{
perror(filename);
exit(1);
}
return 0;
}
But I think that the first code is more clean.
Another option is only change return 1;
into return -1;
(in the first code that I wrote).
What's the best version?
[Question 2]
If I must handle more errors, is it correct a code like this?
int read_file (char *filename, int **vet)
{
FILE *fin;
if ( !(fin = fopen(filename, "r")) )
{
perror(filename);
return 1;
}
* vet = malloc (10 * sizeof(int));
if ( *vet == NULL )
{
perror("Memory allocation error.\n");
return 1;
}
/* ... */
return fclose(fin);
}
int main ()
{
char filename[100];
int *vet;
if ( read_file(filename, &vet) )
exit(1);
return 0;
}