I have a "random-access" file, hardware.dat constructed with 100 entries. What I'm trying to do is use my setRecord() function to modify one of the entrys in "hardware.dat." This is where I'm having problems. No matter what I do I can't get setRecord to modify the file. I thought it might be because I'm opening the file with the "a+" attribute but I'm not sure.
Here is the file I used to generate my random-access file.
Code:
#include <stdio.h>
struct record {
int account;
char name[ 12 ];
int quantity;
float price;
};
typedef struct record entry;
int main()
{
FILE *fPtr;
int i;
entry empty = { 0, "", 0, 0.0 };
if ( (fPtr = fopen( "hardware.dat", "w" )) == NULL ) {
printf( "The file hardware.dat could not be opened" );
}
else {
for ( i = 0; i < 100; ++i ) {
fwrite( &empty, sizeof( entry ), 1, fPtr );
}
fclose( fPtr );
}
return 0;
}
Here is the program with the setRecord function that isn't functioning.
Code:
#include <stdio.h>
void listFile( FILE *ptr, int size );
struct record {
int account;
char name[ 12 ];
int quantity;
float price;
};
typedef struct record entry;
entry getRecord( int num, FILE *ptr );
void setRecord( entry input, FILE *ptr );
int main()
{
FILE *fPtr;
entry tempEntry = { 99, "Eugene", 420, 64.3 };
if ( (fPtr = fopen( "hardware.dat", "a+" )) == NULL ) {
printf( "hardware.dat could not be opened\n" );
}
setRecord( tempEntry, fPtr );
listFile( fPtr, 100 );
return 0;
}
void setRecord( entry input, FILE *ptr )
{
/* -------THIS IS MY TEST PRINTF-------- */
printf( "%d\n", input.account );
fseek( ptr, sizeof( entry ) * input.account, SEEK_SET );
fwrite( &input, sizeof( entry ), 1, ptr );
rewind( ptr );
}
entry getRecord( int num, FILE *ptr )
{
if ( num > 100 || num < 0 )
printf( "getRecord: choose account number between 0 and 99" );
else {
entry output;
fseek( ptr, sizeof( entry ) * ( num ), SEEK_SET );
fread( &output, sizeof( entry ), 1, ptr );
rewind( ptr );
return output;
}
entry temp = { 0, "", 0, 0.0 };
return temp;
}
void listFile( FILE *ptr, int size )
{
entry input;
int i;
for ( i = 0; i < 100; ++i ) {
fread( &input, sizeof( entry ), 1, ptr );
printf( "%d%15s%10d%10.2f\n", input.account, input.name, input.quantity, input.price );
}
rewind( ptr );
}