0

On Windows OS, I have a file with size of 1 MB. I want to use PHP to read the file's content. I know there is the fread function to read file, however, I want to read the file not from the starting position but somewhere at the middle position. How do I do that?

UnholyRanger
  • 1,977
  • 14
  • 24
Saravanan
  • 65
  • 1
  • 2
  • 2
    http://php.net/manual/en/function.fopen.php should be a nice place if you are starting to learn php. – ayush Jul 29 '11 at 04:27
  • @ayush: I viewed the page provided by you but I can't find the file reading at the middle information – Saravanan Jul 29 '11 at 04:30
  • Are you working with a CSV file? Because there is a function for that. – Patrick Jul 29 '11 at 04:47
  • 1
    possible duplicate of [Read a file from line X to line Y ?](http://stackoverflow.com/questions/2808583/read-a-file-from-line-x-to-line-y) – Gordon Jul 29 '11 at 06:22
  • @Gordon: No, you are wrong. My file is a binary file and not CSV file. – Saravanan Jul 29 '11 at 07:15
  • 1
    @Saravanan try the solutions offered please before claiming they are wrong. If they dont solve your problem, update your question to explain what you have tried so far and add that it is a binary file. You didnt say that in your question. Part of getting good answers is adding relevant information. See http://stackoverflow.com/questions/ask-advice – Gordon Jul 29 '11 at 08:44

2 Answers2

3

http://php.net/manual/en/function.fseek.php fseek

Joe
  • 80,724
  • 18
  • 127
  • 145
3

As Joey said, you have tu use fseek.

The following snippet should do (although it is untested):

<?php
$file = fopen("Myfile.txt", 'r');
if (!$file) die('error');

fseek($file, filesize($file)/2, SEEK_CUR); // Position exactly at the middle of the file

/*
 * fread() comes in here
 */
?>

EDIT: instead of filesize();, it would be better to use fstat() and then use the 'size' part of the array. http://www.php.net/manual/en/function.fstat.php

Misguided
  • 1,302
  • 1
  • 14
  • 22