¿Cómo puedo ubicar el puntero de línea en C?

If I read a binary file I can locate n-th line using:

fseek(fp, 4*sizeof(line),SEEK_SET);

But when reading txt file in C, like:

1 1 2.2
2 3 3.001
3 4 5

I can't ensure byte-size of a line because the double value can be 2.2 or 3.0001 or 5 in real cases. This time how can I locate n-th using fseek??

¡Gracias!

preguntado el 28 de agosto de 12 a las 12:08

What's the meaning of line in a binary file? -

@halex: I'm pretty sure it means the thing that would normally be called a fixed-size "record". But if each record ends with a line-feed character, then each record is a line. Although some Windows programs might disagree, requiring CRLF. -

4 Respuestas

Basically you are asking how do you locate n-th line when lines have variable length.

Well, the only way to do this is to go through the file and count the '\n' personajes.

Respondido 28 ago 12, 13:08

The short answer is you cannot do a random seek in a file with variable record length. This is the price one pays when moving to variable record length. You can convert a variable record length to a fixed record length by padding. That comes with additional storage cost though. If random seek is important, it is a worthwhile compromise.

Respondido 28 ago 12, 12:08

You can't; text files don't contain any information about line lengths.

You will need to read each character, and count end-of-line characters. If that's too slow, then you could maintain a separate index of line positions (either in a header in this file, or a separate file), or change your format to use fixed-length records.

Respondido 28 ago 12, 12:08

You can't. You have to read through the file and count the line-endings as you go along; something similar to this:

void GotoLine(FILE* File, unsigned int Line)
{
    int c;

    fseek(File,0,SEEK_SET);
    while (Line>0 && (c=fgetc(File))!=EOF)
    {
        if (c=='\n') Line--;
    }
}

(Note: no error checking :-))

Respondido 28 ago 12, 12:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.