Does fread move the file pointer?

自古美人都是妖i 提交于 2019-11-27 11:19:24

问题


Simple question,

When i use fread:

fread(ArrayA, sizeof(Reg), sizeBlock, fp);

My file pointer, fp is moved ahead?


回答1:


Answer: Yes, the position of the file pointer is updated automatically after the read operation, so that successive fread() functions read successive file records.

Clarification: fread() is a block oriented function. The standard prototype is:

size_t fread(void *ptr,
             size_t size,
             size_t limit,
             FILE *stream);

The function reads from the stream pointed to by stream and places the bytes read into the array pointed to by ptr, It will stop reading when any of the following conditions are true:

  • It has read limit elements of size size, or
  • It reaches the end of file, or
  • A read error occurs.

fread() gives you as much control as fgetc(), and has the advantage of being able to read more than one character in a single I/O operation. In fact, memory permitting, you can read the entire file into an array and do all of your processing in memory. This has significant performance advantages.

fread() is often used to read fixed-length data records directly into structs, but you can use it to read any file. It's my personal choice for reading most disk files.




回答2:


Yes, calling fread does indeed move the file pointer. The file pointer will be advanced by the number of bytes actually read. In case of an error in fread, the file position after calling fread is unspecified.




回答3:


Yes, The fp will be advanced by the total amount of bytes read.
In your case the function fread reads sizeBlock objects, each sizeof(Reg) bytes long, from the stream pointed to by fp, storing them at the location given by ArrayA.




回答4:


Yes, it does. It could be checked by using ftell() function in order to show current position (in fact, bytes read so far), take a look it:

int main() {

    typedef struct person {
        char *nome; int age;
    } person;

    // write struct to file 2x or more...

    FILE *file = fopen(filename, "rb");
    person p;
    size_t byteslength = sizeof(struct person);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    //...

    fclose(file);

    return 0;
}


来源:https://stackoverflow.com/questions/10696845/does-fread-move-the-file-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!