Reputation: 25
I have a file inp which looks like:
123.456 one
111.111 two
222.222 three
444.444 four
I'm trying to read this file like:
while(fscanf(inp, "%s %s", s1, s2) != EOF)
Where 123.456
stores in s1
(string) and "one"
stores in s2
(string).
But I get this error:
Thread 1:EXC_BAD_ACCESS (code = 1, address = 0x48)
Any idea why or how to fix this error?
Here is my whole code:
int main(void)
{
FILE *inp;
char s1[15];
char s2[8];
inp = fopen("inputfile.txt", "r");
while(fscanf(inp, "%s %s", s1, s2) != EOF)
{
printf("%s", s1);
}
return 0;
}
My debugging area shows that "123.456" is stored into s1 and "one" is stored into s2.
Upvotes: 0
Views: 650
Reputation: 882226
There's nothing wrong with that code, other than the missing stdio.h
include (a). Therefore your problem either lies elsewhere (such as if you're compiling a different file) or your compiler is buggy (unlikely).
You can find out if it's the first one by simply making a minor change:
#include <stdio.h>
int main (void) {
FILE *inp;
char s1[15];
char s2[8];
puts ("Hello from Pax");
inp = fopen ("inputfile.txt", "r");
if (inp == NULL) {
puts ("Couldn't open input file");
} else {
while (fscanf (inp, "%s %s", s1, s2) != EOF) {
printf ("[%s] [%s]\n", s1, s2);
}
}
return 0;
}
and seeing if the new message comes out. The change I'm suggesting for debugging is simply the Hello from Pax
output but I've cleaned up the code a little more as well to catch some possible problems.
On my system, that code outputs:
Hello from Pax
[123.456] [one]
[111.111] [two]
[222.222] [three]
[444.444] [four]
as expected.
(a) One possibility to watch out for is missing include files in systems where int
and pointers are different widths. If you have a compiler that assumes unprototyped functions accept int
arguments, that may lead to parameters being extracted from the wrong place on the stack.
This answer shows this particular little foible in action for mismatched printf
format specifiers and it's possible you may see the same behaviour from fscanf
since it uses the same feature.
But that's just educated supposition on my part, it may not apply here.
Upvotes: 2