Question

I need to identify if I am at the top of the file just wondering for binary files do they have something similar to eof at the top ?

Était-ce utile?

La solution

A file does not contain "EOF" at all. EOF is just a special value returned from fgetc() and other functions when they detect the end of the file. The end of the file is detected through other means, such as by read() returning 0 (or returning less than the requested number of bytes, if you are reading a regular file).

If you are using plain C, you can use ftell() to figure out if you are at the beginning.

Autres conseils

fseek(pFile, 0, SEEK_SET); will take you to the beginning of a file that you've opened, assuming a call to fopen has been successful.

Another way to determine if you're at the beginning of a file is to call pos = ftell(pFile);. If pos is 0, you are at the beginning of the file.

Simple code example:

int main(void)
{
    FILE *fp;
    long pos=-1;
    fp = fopen("c:\\file.exe", "rb");

    pos = ftell(fp);//tells you the position of the file ptr. 
                    //For this example, if file exists, pos would be 0
    fclose(fp);

    return 0;   
}

See also ftell, rewind, fseek, (etc, searchable page)

In most operating systems, “a file is a file is a file” and there is no distinction between text files and binary files at the operating system level. The Microsoft Windows (and, earlier, DOS) family is a notable exception.

In general, there is neither a “beginning of file” nor an “end of file” marker of any kind in the file itself: when you open a file, the file pointer is positioned at the beginning of the file; when the end of the file is reached on reading, EOF (usually -1) is returned, but this is done automagically by the OS when it reaches the end of the file (which it knows from the file's size), not because there is any kind of marker in the file itself.

A vaguely related concept, which you might be interested in, is the idea of “file magic”. Different file formats (JPEG, PNG, PDF, etc.) typically use a number of bytes at the beginning of the file to identify the file type and version (all PDF version 1.5 files, for example, begin with “%PDF-1.5\n”). There is, unfortunately, no standard for this, so there are occasionally “collisions”, where two distinct file formats can have the same “magic”. The Linux/Unix utility file uses a database of file magic to identify many file types successfully from the initial bytes, but it is not always successful for less common file types

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top