I am learning C, so I decided to try out r/w-ing to other files. Can
anyone please tell me why I get the following error when running the
program?
Transcript:
Name?
Nikhil R. Mulani
Bus error
#include <stdio.h>
main()
{
char name[60];
FILE *Fp;
Fp = fopen("/deeter.dat", "w");
fprintf(Fp, "Name: %s\n", name);
int fclose( FILE *Fp );
}
There are several problems with your program of different importance.
1) main() is supposed to return an int. While you will get away without
specifying a return type on older compilers (i.e. non-C99) you should
avoid that and use either
int main( void )
or
int main( int argc, char *argv[ ] )
2) You never test if the call of fopen() succeeds. But when it fails
'Fp' will be set to NULL and you can't write to the file.
3) Using scanf() to read in strings is tricky. First of all, when
you just have a "%s" conversion specifier you can't avoid that
the user enters more characters than fit into the buffer into
which the result gets written - and if (s)he does you write past
the end of that buffer, which is a very bad mistake. Thus you
should call it at least with
scanf( "%59s", name );
That way the user can't enter more than 59 characters (you need
the 60th for the final '\0' character).
Another problem is that scanf() stops at white space (i.e spaces,
tabs etc.). This will keep you from entering "Nikhil R. Mulani"
since scanf() will stop reading after the "Nikhil". While that
can be circumvented by using
scanf( "%59[^\n]", name );
it probably is simpler to use fgets() to read in the whole line.
4) Since you didn't check that 'Fp' isn't NULL you might get into
problems with the call of fprintf() - this expects a valid FILE
pointer as the first argument.
5) The line
int fclose( FILE *Fp );
should get the compiler upset (and I strongly doubt that you got
the program compiled in the for you posted it). I guess you want
fclose( Fp );
here - but don't call fclose() when 'Fp' is NULL.
6) Since main() is supposed to return an int your program is missing
a return statement at the end.
Regards, Jens