Paratrpr173
Paratrpr173

Reputation: 3

C: How to properly output struct from .txt file?

First time I have asked a question here. First here's the code:

void displayCompanyInfo(STAFF  e[], int *s)
{
    FILE *payRoll;
    int i = 0;
    int rosterNumber [100];
    int count = 1;

    if ((payRoll = fopen("payRoll.txt", "r")) == NULL)
    {
        perror ("error");
        exit (0);
    }

    cls;

    while (fgets(e[i].name,  sizeof(e[i].name), payRoll) != NULL)
    {
        printf ("Record %i: ", count++);
        printf("%s\n", e[i].name);
    }

    fclose(payRoll);
    printf("\n\n");
    pause;
    cls;

} // end of display

Basically this code works. However when the text file displays it reads like this:

Record 1: Name: blah
Record 2: Age: 23
Record 3: Hourly Rate: 34

Instead I want it to read it as follows:

Record 1: Name: Blah
Age: 23
Hourly Rate: 34

Record 2: Name: Blah2
Age: 24
Hourly Rate: 35

And so on...

Any idea on how I can get this to work. I didn't post whole program because I didn't want to over do my thread. But if you need it let me know.

Upvotes: 0

Views: 205

Answers (2)

Hitesh Menghani
Hitesh Menghani

Reputation: 987

To this case you have to work with binary file handling.With text file it is not possible. You have to read,write chunk of data in terms of bytes and handle it accordingly to retrieve you structure.

Say

struct e{ char name[20], int age, int hourly_rate };

This structure will require 20(name) + 4(age) + 4(hourly_rate) bytes.Then you should write 28 bytes at a time in binary file and retrieve 28 bytes accordingly,which is not possible in case of text file.Because text file considers every thing as character,say age=23 it considers age field as 2 bytes and if age=3,it consider it as 1 byte.But binary file considers both thing as 4 bytes which is actual size of integer.

So the solution to your problem is binary file handling.

Upvotes: 2

hdante
hdante

Reputation: 8020

The problem is that the loop considers each line as a record. Instead, a record should be 3 lines. So read 3 things in the loop - add the 2 missing right before the printf.

Upvotes: 1

Related Questions