Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading a text file into an array

Status
Not open for further replies.

bob15

Programmer
Mar 25, 2002
1
IE
How can I read a text file (source.txt) into an array, in order to read the characters in the file
 
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 &quot;p&quot; points to...
if(*p == '\0')
... p points to a null byte...
else
... p points to some data byte...

p++;
}
}
 
For text files, fgets() (obtains the next line from the file). For binary files, fread() (obtains the next &quot;chunk&quot; 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.

(error checking omitted)

#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

struct stat stbuf;
unsigned char *p; /* for text files, char *p; */
int fd;
const char path[]=&quot;source.txt&quot;;

stat(path,&stbuf);
p=malloc(stbuf.st_size);
fd=open(path,O_RDONLY);
read(fd,p,stbuf.st_size);
close(fd);
free(p);
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top