using gawk Consider the following file called elems.txt : This file contains a l
ID: 3890219 • Letter: U
Question
using gawk
Consider the following file called elems.txt:
This file contains a list of the elements in the periodic table. Each field in this file is separated by a comma and each record is separated by a newline character. First, write a one-line gawk script that prints out just the record number and the element symbol (e.g., He) of all the elements in the list that contain the pattern "ium", without the quotes. Then, write another one-line gawk script that prints just the total number of lines that contain the pattern "ium”, without the quotes.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct
{
int AtomicNo;
char *ChemSymbol;
char *ChemName;
float AtomWeight;
char *roomState;
char *Bonding;
char *YearDisc;
} ELEMENT;
void printrecord(FILE *fp, ELEMENT *arr, int i)
{
fprintf(fp, "---------------- ");
fprintf(fp, "| %d %f ", arr[i].AtomicNo, arr[i].AtomWeight);
fprintf(fp, "| %s %s", arr[i].ChemSymbol, arr[i].ChemName);
fprintf(fp, "| %s ", arr[i].roomState);
fprintf(fp, "| %s ", arr[i].Bonding);
fprintf(fp, "| Found : %s ", arr[i].YearDisc);
fprintf(fp, "---------------- ");
}
int main(int argc, char* argv[])
{
FILE *fpi, *fpo;
char* line;
char* elems[argc-1];
ELEMENT arr[118];
int i,j;
int elemslen;
if(argc < 2)
{
printf("ERROR : please provide at least one program argument ");
exit(1);
}
if(argc > 2)
{
if(strchr(argv[1], '.') != NULL)
{
if(!(fpo = fopen(argv[1], "w")) == NULL)
{
printf("Unable to open output file, %s, for writing. Exiting ....", argv[1]);
exit(1);
}
for(i = 2; i < argc; i++)
strcpy(elems[i-2], argv[i]);
}
else
for(i = 1; i < argc; i++)
strcpy(elems[i-1], argv[i]);
}
else
strcpy(elems[0], argv[1]);
if((fpi = fopen("element_db.txt", "r")) == NULL)
{
printf("Unable to open file. Exiting . . .");
exit(1);
}
i = 0;
while(fgets(line, sizeof(line), fpi) != NULL)
{
arr[i].AtomicNo = atoi(strtok(line, ","));
strcpy(arr[i].ChemSymbol, (strtok(NULL, ",")));
strcpy(arr[i].ChemName, (strtok(NULL, ",")));
arr[i].AtomWeight = atof((strtok(NULL, ",")));
strcpy(arr[i].roomState, (strtok(NULL, ",")));
strcpy(arr[i].Bonding, (strtok(NULL, ",")));
strcpy(arr[i].YearDisc, (strtok(NULL, ",")));
i++;
}
fclose(fpi);
elemslen = sizeof(elems)/sizeof(elems[0]);
if(fpo == NULL)
fpo = stdout;
for(i = 0; i <elemslen; i++)
{
for(j = 0 ; j < 118; j++)
{
if(strcmp(elems[i], arr[j].ChemSymbol) == 0)
break;
if(j < 118)
{
printrecord(stdout, arr, j);
}
else
fprintf(fpo, "WARNING : No such element: [%s] ", elems[i]);
}
}
if(fpo != NULL && fpo != stdout)
fclose(fpo);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.