There are at least a half a dozen ways to do this
and here's one...
In your program, setup a character pointer and an array
buffer of some size...
char *p, buf[1024];
...then open the file for reading...
fd = open(...)
...then read into the buffer...
while(read(fd, (void *)buf, sizeof(buf)-1) > 0)
{
...in this while loop you can...
p = buf;
for (i = 0; i < sizeof(buf), i++)
{
...in here you can process whatever "p" points to...
if(*p == '\0')
... p points to a null byte...
else
... p points to some data byte...
For text files, fgets() (obtains the next line from the file). For binary files, fread() (obtains the next "chunk" of the file). Both of these methods are in the standard C library.
If you want to read the entire file, all at once, into memory, the easiest way is probably to obtain the file's size and then use malloc() to assign a block of allocated memory of that size. Then you would open the file and read the entire thing into the allocated memory. It's awkward to obtain file size using only the standard library, so using a system extension may be preferable. On POSIX systems, you can use stat as in the example below.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.