For reading lines from a file, I usually start with a shell like this.
Code:
#include <stdio.h>
int main()
{
static const char filename[] = "file.txt"; /* "parts.dat" */
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
char line[BUFSIZ];
while ( fgets(line, sizeof line, file) != NULL )
{
/* ... */
}
}
else
{
perror(filename);
}
return 0;
}
Then you can add stuff and make adjustments. For example, reading elements of a structure -- and as proof that things are working, just print them out.
Code:
#include <stdio.h>
#define MAX 100
typedef struct
{
int partnum;
char partdescription[50];
int qty;
float price;
} part;
int main()
{
static const char filename[] = "file.txt"; /* "parts.dat" */
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
char line[80];
part item[MAX];
int i = 0;
while ( fgets(line, sizeof line, file) != NULL )
{
if ( sscanf(line, "%d *%79[^*]* %d %f",
&item[i].partnum,
item[i].partdescription,
&item[i].qty,
&item[i].price) == 4 )
{
printf("partnum = %d, description = %s, qty = %d, price = %.2f\n",
item[i].partnum,
item[i].partdescription,
item[i].qty,
item[i].price);
++i;
}
}
}
else
{
perror(filename);
}
return 0;
}
Then continue adding and modifying as necessary.