Getting extra characters while reading records from a file using structure.

Jitendra Kumar Chauhan 26 Reputation points
2021-06-09T09:50:02.503+00:00

I wrote a C program to read records from a file using structure but when i compiled it i got few extra characters apart from those which are written in my file "EMPLOYEE". So Please resolve my issue. Screenshot of the file content and debug console has been attached herewith.103805-debug-console-screenshot.png103806-file-content-screenshot.png
Here is the C Program---

include<stdio.h>

include<conio.h>

include<stdlib.h>

int main()
{
FILE* fp;
errno_t err;
char another = 'Y';
struct emp
{
char name[31];
int age;
float bs;
};
struct emp e;
err = fopen_s(&fp, "EMPLOYEE.DAT", "r");
if (err != 0)
{
puts("Can Not Open file");
exit(1);
}
else
while ((fscanf_s(fp,"%s%d%f",e.name, sizeof(e.name), &e.age, &e.bs)) != EOF)
printf("%s%d%f\n", e.name, e.age, e.bs);
fclose(fp);
return 0;
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,906 questions
{count} votes

Accepted answer
  1. RLWA32 48,151 Reputation points
    2021-06-09T10:30:01.45+00:00

    Assuming that the first 2 characters are name, the next two characters are age and the remainder of the line is the bs float try this -

            while ((fscanf_s(fp, "%2s%2d%f", e.name,  (unsigned int) _countof(e.name), &e.age, &e.bs)) != EOF)
                printf("%s %d %f\n", e.name, e.age, e.bs);
    

1 additional answer

Sort by: Most helpful
  1. Guido Franzke 2,191 Reputation points
    2021-06-09T10:08:23.51+00:00

    Hello,
    did you check the variables with the debugger?
    IMO, fscanf is the wrong approach. %s will read the full string "lk2587000.0000" . To separate the values to "lk", 2587000 and 0.0 , you must implement your own string analysis routine.
    Regards, Guido
    In addition: it is always usefull to initialize the values of a variable/struct/etc.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.