#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct artikel {
  int artnr;
  char namn[256];
  int saldo;
  float pris;
};

char sbuff[256]; //buffer for sprintf to write to.

struct artikel artikel1;

int main (){
  int i;
  while (1){ //infinite loop

    scanf("%d", &artikel1.artnr);
    //printf("%d\n", artikel1.artnr);
    while(getchar()!='\n'){ //here the looping getchar function eliminates the remaining characters in the data stream, namely the \n character, which prevents the next read from working as intended.
      ; //the main body of the function is empty as we only require the function call 'getchar()' in the loop condition.
    }
    scanf("%[^\n]s",artikel1.namn); //[^\n] is a regular expression, meaning the 'negative character set of \n'; includes all characters except '\n'
    scanf("%d", &artikel1.saldo);
    scanf("%f", &artikel1.pris);
    
    FILE *fp;
    fp = fopen("artiklar.dat","a"); 
    if (fp == NULL){ //on error, "fopen" returns 'NULL'
      fprintf(stderr, "File not found.");
      exit(1);
    }else{
      sprintf(sbuff, "%d;%s;%d;%.2f;", artikel1.artnr,  artikel1.namn,  artikel1.saldo,  artikel1.pris);
      fprintf(fp, "%s", sbuff);
      fclose(fp);
      printf("Successful write to file\n.");
    }
  }
}
