> I am trying to migrate my app from Windows to Linux (since C++ is sooooo portable...)
You mis-understand portable then.
1. simply writing it in C or C++ does not make it portable.
2. the fact that it works on one implementation does not make it portable.
> pos = (66 * count); // length of record times nmbr of previous records
> fsetpos( stream, &pos );
fpos_t is an opaque type, you don't know what is really underneath. The only thing you can do is initialise it with fgetpos and use it with fsetpos. Anything else is wrong and non-portable.
Code:
fgetpos( fp, &pos );
// some code here
fsetpos( fp, &pos );
So, I think your code should be like this - I've also fixed your feof() problem as well
Code:
int addCredit(char *number_in, long amount)
{
char buff[BUFSIZ];
FILE *stream;
int count = 0;
fpos_t pos;
char account_in[10];
char name_in[20];
char last_in[20];
long balance = 0;
printf("Buscando: %s\n", number_in);
// Attempt to open the file. If it returns NULL fails. exit with condition 1
if ((stream = fopen(FullFileName, "r+")) == NULL)
return 1;
/* Cycle until end of file reached:or record found */
fgetpos( stream, &pos ); // the initial position
while ( fgets( buff, sizeof buff, stream ) != NULL ) {
int numvals;
// improve sscanf call, so you don't buffer overflow your strings.
numvals = sscanf(buff, "%s %s %s %d", account_in, name_in, last_in, &balance);
if ( numvals != 4 ) {
// some error message
}
if ((strcmp(account_in, number_in)) == 0) // if they are identical
{
printf("Encontrado...");
fsetpos(stream, &pos); // back to start of record
// ------------- modify amount and save it -----------------
fprintf(stream, "%10s %20s %20s %10ld\n", account_in, name_in,
last_in, balance + amount);
fclose(stream);
return 0;
}
// now pointing at the start of the next record
fgetpos( stream, &pos );
// Count number of records read
count = count + 1;
}
printf("Registro no existe. Total registros: %d\n", count);
fclose(stream);
return 1;
}