How to read in file size
Christopher North-Keys
harp at cadillac.CAD.MCC.COM
Wed Jun 13 01:07:09 AEST 1990
> I am using BSD Unix 4.2 on Sun 3's, a Sparc, and on a Encore multimax. I
> do not think this is a machine dependent question, but this info is for
> anyone who might flame me later for not specifing it.
>
> I am aware of the wc (word count) program in unix. I can use something
> like this in my C program.....
> system ("wc -c filename") ;
No! (blech!)
See the library function "fstat". A code fragment from SunOS follows.
The reference to the file size is the line:
if((*addr_buffer=(char *)calloc(1, statbuf.st_size+1))==NULL)
^^^^^^^^^^^^^^^
#-------------------------------------------------------------------------
/* I haven't check this include-list for non-essentials */
#include <stdio.h>
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include "stdelf.h"
long
SwallowFile(addr_buffer, path) /* North-Keys, 1989 */
char **addr_buffer, *path;
{
struct stat statbuf;
int in_count;
int fd = -1;
/* Attempt to open desired file */
if(((fd)=open(path, O_RDONLY))==-1)
{
(void)fprintf(stderr, "SwallowFile: %s not opened\n", path);
return (FAIL);
}
if(fstat(fd, &statbuf)==-1)
{
(void)fprintf(stderr, "SwallowFile: error on fstat file %s\n", path);
return (FAIL);
}
/* Get a buffer to fit */
if((*addr_buffer=(char *)calloc(1, statbuf.st_size+1))==NULL)
{
(void)fprintf(stderr, "SwallowFile: no space for calloc\n");
return (FAIL);
}
/* Read in the file */
if((in_count = read(fd, *addr_buffer, statbuf.st_size)) != statbuf.st_size)
{
(void)fprintf(stdout,
"SwallowFile: error(?) %d/%d bytes read from %s\n",
in_count, statbuf.st_size, path);
(void)free(*addr_buffer);
return (FAIL);
}
return (in_count);
}
--
--Christopher Alexander North-Keys----/\--------------------------------------
Co-founder Group Talisman / \/\ ^*^ Harp[@Mcc.Com]
[*my* opinions] / \ \ Associate Systems Analyst
--------------------------Microelectronics & Computer Technology Corporation--
More information about the Comp.lang.c
mailing list