-
read/write files
Hi all,
I have a problem with some read/write functions.
I have a .bin file which contains a lot of structures as follows:
Code:
struct alumno
{
char id[10];
char apellido1[32];
char apellido2[32];
char nombre[32];
float nota1p;
float nota2p;
float notamedia;
char photofilename[20];
};
What I have to do is read the file, firstly one structure by one, and then all the file at once and change the value if notamedia is less than 3. I'm using read() and lseek(), but I'm very loss :(. Somebody can give me a hand in developing the code. I believe is not too big.
Thanks in advance for the help
-
Do you understand what serialization is and how data structures are stored in a binary file?
You will not find the number "3" (or 3.0) at the location of the notamedia member. You will find a 4 byte binary value (presuming the program that wrote the file used 4 byte floats), the exact same way a variable is stored in memory.
-
I take it there are a lot of assumptions made against this binary file you need to work with that comprises the data needed to fill such a structure? You will need to know at what point in your binary file that will be populating your float type for notamedia variable.
-
Thanks for the reply, I will try to clarify some points:
have 3 files.
First one a header with the struct and function definition:
Code:
typedef struct
{
char id[16];
char name32];
float nota1p;
float nota2p;
float notamedia;
char photofilename[20];
int photosize;
char photodata[16000];
}evaluation;
int review(int fd);
Second one with the main()
Code:
main()
{
int fd;
struct timeval t1, t2;
double secs;
int modify;
fd=open("datos.bin", O_RDWR, S_IRWXO);
printf("File Descriptor: %d\n", fd);
gettimeofday(&t1, NULL);
secs=t1.tv_usec/MICROX;
printf("time 1: %.6f \n",secs);
modify=review(fd);
gettimeofday(&t2, NULL);
secs=t2.tv_usec/MICROX;
printf("time 2: %.6f \n",secs);
In this one I'm trying to measure the time before and after the function, but is not working very good.
I also open the file
Third one with the function
Code:
#include </home/midori/arqui/header.h>
int review(int fd)
{
int nbytes;
void *buf;
nbytes=read(fd,buf,sizeof(evaluation));
}
The problem is that nbytes is different each time I run the program.
I want to read each structure in the file and then manipulate it, but I'm not sure how I can pass the struct to the function review() and how to use lseek to find a value of evaluation->notamedia < 3.
The main point is how can I manage the .bin file, I cannot even edit it to see how the data is structured there. So I cannot figure out how to use a function to find a specific data inside.
Maybe a pointer that which contais a 3.5 or bigger in binary format? lseek() function?
Thanks a lot for your help
-
What other headers are you using and how have you declared 'evaluation" parameter passed in to your read()?
I would also prefer you work with file I/O in c:
Cprogramming.com - Tutorials - C File I/O