Re: File-handling

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



gustav@xxxxxxxxxxxxxx wrote:
> Hi there!
>
> Can someone explain the major difference between fgets and fopen? Which is
> the best together with plain textfiles? and why?

fgets can be handy to read a large file one LINE at a time.

This is most useful in files that are line-based, such as SQL data dumps,
CSV files, text files, config files, etc. when you want to process their
contents a line at a time and do something to the data.

fget lets you read an arbitrary amount of data -- this is useful if you
just want to transfer the data from point A to B without interpreting it,
or if the data is binary and has some sort of internal byte-structure you
need to tear apart to process it.

For small files, you might as well just use http://php.net/file or other
functions that deal with the whole file at once -- You only really want to
mess with fopen/fget|fgets/fclose if you have files that could potentially
be HUGE, and you can read a chunk at a time, deal with it, and read some
more -- Avoiding trying to suck the whole thing into RAM all at once.

> When using fget. Is it something special you should think when taking care
> of line-breaks? (/n, /r/n ...)

If your data could potentially be coming from Mac, PC, and/or Linux
instead of just one platform, you'll have to write some code to figure out
what to do with line-breaks.

Since I'm always on Linux servers, I generally do:

$data = str_replace("\r\n", "\n", $data); //PC -> Linux
$data = str_replace("\r", "\n", $data); //Mac -> Linux

This converts everything to Linux format, which is what I'll use internally.

Note that the order of the two lines is crucial -- If you flip-flop them,
you'll make a real mess.

If you're not trying to change the data, nor interpret it, you needn't
worry about the newlines.

> eof and feof. What's the difF? *don't get it*

EOF is an acronym for End Of File.

feof is the function used to determine if a file has reached its EOF --
that is, if you have successfully read all of the data, and there is no
more data to read, and the file still seems kosher, so you're DONE.


-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux