I have a text file containing 20 lines of text (number and name). I want to read these from the text file and then use them as parameters in a function.
My text file contains some 20 lines like this one below:
719 Chris
I have the following code but it doesn't work, and gives an EXC_BAD_ACCESS (code=1, address=0x68)
void read() {
int number;
char name;
char buffer[200];
FILE *fp = fopen("text.txt", "r");
while (fgets(buffer, sizeof(buffer), fp)) {
printf("%d %s\n", &number, name);
add(name, number)
}
fclose(fp);
}
CodePudding user response:
You are not checking whether the file was opened successfully. If fopen returns NULL and that value is stored in fp, then the function call fgets(buffer, sizeof(buffer), fp) will invoke undefined behavior (i.e. your program may crash).
Also, the line
printf("%d %s\n", &number, name);
will invoke undefined behavior, for two reasons:
The
%dconversion format specifier requires that you pass an argument of typeint, but you are instead passing an argument of typeint*.The
%sconversion format specifier requires that you pass an argument of typechar *, but you are instead passing an argument of typechar.
Passing name also does not make sense, because it has never been assigned a value. You probably want to do something with buffer instead, as that contains the line that you just read using fgets.
My guess is that you want to use the function sscanf instead of printf, like this:
sscanf( buffer, "%d %s", &number, name);
However, in that case, you must change name to an array, so that it can store several characters, instead of only a single character.
Here is the full code, which fixes all issues mentioned above:
void read()
{
int number;
char name[200];
char buffer[200];
FILE *fp = fopen( "text.txt", "r" );
if ( fp == NULL )
{
fprintf( stderr, "Error opening file!\n" );
exit( EXIT_FAILURE );
}
while ( fgets( buffer, sizeof buffer, fp ) != NULL )
{
if ( sscanf( buffer, "%d %s", &number, name ) != 2 )
{
fprintf( stderr, "Parsing error!\n" );
exit( EXIT_FAILURE );
}
add( name, number );
}
fclose(fp);
}
Note that you will have to #include <stdlib.h> in order to use the function exit.
CodePudding user response:
I see several points that seem odd to me:
What does the
add()function do and why doesn't it have a semicolon at the end? (likeadd(name, number);)You should add a
fclose(fp);to close the stream.In your
printf()you use the flag%sto print a char, except that%sprints a string, replace by%c.You try to print the address of number via
&number, except that it is the%pflag and not the%dflag to do it.numberandnamelook empty (and uninitialized!) at least at the first pass inprintf().
