Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

reading table with chemical elements in structure

Thierry DesotThierry Desot Member Posts: 1

HI

I am new to C.
I try to write a script that reads chemical elements into a structure, write to a binary file, where the elements are classified according to the number in the third column. I should try to do that with fseek function.
I could write the elements into a structure in binary file, but don't succeed to classify on the 2nd column.

  1. input file with element

Actinium Ac 89 227.0278
Aluminum Al 13 26.981539
Americium Am 95 243.0614
Antimony Sb 51 121.760
...

  1. my script

include <stdio.h>

include <stdlib.h>

include <string.h>

struct Element {

char nom[44];
char symbole[4];
int numeroatomique;
double masseatomique;

};

typedef struct Element FICHE;

int main() {

char line[300];
FICHE element  = {"","",0,0};
char nom[44];
char symb[4];


FILE *pf = NULL;
FILE *mendelf;

if ( ( pf = fopen ( "tabletriee.txt", "r")) == NULL) {
    printf ( "could not open file\n");
    return 1;
}
if ( ( mendelf = fopen( "elements.DAT", "wb")) == NULL) {
    printf ( "could not open file\n");
    return 1;
}
while ( ( fgets ( line, sizeof ( line), pf))) {
    if ( ( sscanf ( line, "%44s %4s %d %lf", element.nom, element.symbole, &element.numeroatomique, &element.masseatomique)) == 4) {

        fwrite(&element, sizeof(element), 1, mendelf);

    }
}
fclose (pf);
fclose (mendelf);
int rec;    
mendelf = fopen("elements.DAT","rb");


while(fread(&element,sizeof(element),1,mendelf))

 printf("%s\t%s\t%d\t%lf\n", element.nom, element.symbole, element.numeroatomique, element.masseatomique);          

return 0;

}

  1. expected output should be

Aluminum Al 13 26.981539
Antimony Sb 51 121.760
Actinium Ac 89 227.0278
Americium Am 95 243.0614

Thanks for helping!!

Sign In or Register to comment.