Pregunta

I have a file containing a list of parts and part numbers. What I need to do is display the name of the part at a location given by a file pointer and an integer. Something like sizeof(part) * n and then display the information for the part at that location.

I am trying fseek and fread but it does not seem to be working properly.

FILE * ofp;
ofp = fopen("file.bak", "r");

char p[sizeof(part)];

fseek(ofp,sizeof(part) * 4,SEEK_SET);
fread(p, sizeof(part), 1, ofp);
printf("%s", p);

It prints the first part on the list, when it should be printing the 4th.

The part is a structure containing 3 fields. They are of the form:

1 item1 2
4 item2 80

where the first number is the item number and the second is the number in stock, so they are not all the same length. They are however converted to a binary file, that is the ofp.

¿Fue útil?

Solución

Here's what I was thinking for you to try:

FILE * ofp;
ofp = fopen("file.bak", "r");
part seek_part;

memset( &seek_part, 0, sizeof(part) );
fseek(ofp,sizeof(part) * 4,SEEK_SET);
fread(&seek_part, sizeof(part), 1, ofp);
printf("%s", seek_part.name);

This still won't compile, but you should get the idea. We'd need to see the part typedef to be able to really show the correct printf().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top