Code:
#include <stdio.h>
#include <string.h>
struct storagemanipulation
{
char namn[100];
int lagersaldo;
int varunummer;
};
void readFromFile(FILE *fp, int antal_varor, struct storagemanipulation *inventory)
{
for (int i = 0; i < antal_varor; i++)
fscanf(fp,"%s %d %d",inventory[i].namn, &inventory[i].lagersaldo, &inventory[i].varunummer);
}
void saveToFile(FILE *fp, int antal_varor, struct storagemanipulation *inventory)
{ // the file should already be open for writting as well
// so is there an actually needed to open it again?
//
//
// your data should be stored in your struct array
// just pass that and its size to write the data
//into the file
fseek(fp,0,SEEK_SET); // just to be sure it at the start of file
// which ever order they are suppose to go, it needs to match the file
for (int i = 0; i < antal_varor; i++)
{
fprintf(fp, "%s %d %d\n", inventory[i].namn, inventory[i].lagersaldo, inventory[i].varunummer);
}
}
int main (void)
{
struct storagemanipulation inventory[4];
char file[30], buffer[1024], name[100];
int count = 0, size;
FILE *fp;
printf("Enter filename\n");
scanf(" %s", file);
//Open for append; open
//(or create if the file does not exist)
//for update at the end of the file.
if ((fp=fopen(file,"a+") ) == NULL )
{
printf("cannot create file\n");
return -1;
}
// check to see if file is empty
// for first open if it is a fresh file.
// just to play it safe.
fseek (fp, 0, SEEK_END); // go to end of file
size = ftell(fp); // get size
// put back to front of file just in case
// that part all depends on how your file is, if it is a new file,
//already has information in it, and you do not want to over write it
// then you'll need to set it accordingly.
fseek(fp,0,SEEK_SET);
if ( size == 0 )
{
printf("File is empty\n"
"please add data to file\n");
while ( count < 4)
{
printf("enter name, item nuber, and number\n");
fgets(buffer, sizeof buffer, stdin);
scanf(" %s%d%d", strcpy(inventory[count].namn,name), &inventory[count].lagersaldo,
&inventory[count].varunummer);
count++;
}
}
else
readFromFile(fp, 4, inventory);
saveToFile(fp, 4, inventory);
for ( int f = 0; f < 4; f++)
printf("%s %d %d\n", inventory[f].namn, inventory[f].lagersaldo,
inventory[f].varunummer);
fclose(fp);
return 0;
}