Given the declaration:
char nextIn[3];
This code is wrong:
if ((fscanf(mioHashFile,"%d",nextIn) == -1) || (fscanf(mioHashFile,"%d",nextIn) == 0) ||
(fscanf(mioHashFile,"%d",nextIn) == 1))
{
You are passing an array of three characters and expecting fscanf()
to treat it as an int
. Your conditions are odd, too. EOF is not guaranteed to be -1
(though I don't recall a system where it was not). There wouldn't be much point in trying again after detecting EOF (not without other activity to clear the EOF marker).
When I try this
fscanf(mioHashFile,"%s",nextIn); if (strcmp(nextIn, '-1') == 0)
it still crashes and burns opulently due to type incompatibility. @Emmet also caught my error on the EOF (in that answer's code). How would you do it, and still maintain thescanf()
,printf()
formatting that I'm trying to use?
That requires some semi-real coding. I'd use fgets()
and sscanf()
rather than fscanf()
:
char line[4096];
int lineno = 0;
while (fgets(line, sizeof(line), mioHashFile) != 0)
{
if (++lineno == 1)
continue; // Skip the offset line
if (line[0] == 'O') // Overflow line - skip
continue;
if (sscanf(line, "%d %9s %20s %f", &nDeleteSwitch, sSSN, sName, &nSalary) != 4)
{
fprintf(stderr, "Failed to scan data from: %s", line);
continue;
}
if (nDeleteSwitch == 0)
printf("%-11s%-21s%-10.2f\n", sSSN, sName, nSalary);
else if (nDeleteSwitch == -1)
printf("there's a -1 on row: %d\n", lineno);
else
printf("The delete switch value is %d\n", nDeleteSwitch);
}
Note that %s
skips leading white space and then stops scanning at the next white space.